angular 6 custom element directives

為{幸葍}努か 提交于 2020-01-06 07:08:30

问题


How can one create an element directive in angular 6? I see how to create an attribute directive, but what if I want to create a custom element?

@Directive({
  selector: '[appCards]'//you can't do something like -- element: name
})
export class CardsDirective {

    constructor(el: ElementRef) { 
}
}

回答1:


I tried creating a Directive with Selector as and it works. Angular is so powerful.

import {Directive, ElementRef, Input} from '@angular/core';

@Directive({
  selector: '<appCards>'
})
export class CardsDirective {

    @Input() label;
    constructor(el: ElementRef) { 
      console.log('it called');
    }

    ngOnInit(){
      console.log(this.label);
    }
}

Template:

<appCards label="change"></appCards>

https://stackblitz.com/edit/angular-av5x68




回答2:


In angular, you can create element directive in following way

@Directive({
  selector: 'appCards'
})
export class CardsDirective {

    constructor(el: ElementRef) { 
    }
}

You only have to remove the [] brackets in the selector , in order to make it element directive.



来源:https://stackoverflow.com/questions/52980832/angular-6-custom-element-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!