简体   繁体   中英

angular 6 custom element directives

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) { 
}
}

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

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.

According to Angular Documentation, you can declare the selector as one of the following ways. So if you want to create an element with directive, you have to declare the selector of the directive as

selector: 'elementName'

  • element-name: Select by element name. .class: Select by class name.
  • [attribute]: Select by attribute name. [attribute=value]: Select by
  • attribute name and value. :not(sub_selector): Select only if the
  • element does not match the sub_selector. selector1, selector2: Select
  • if either selector1 or selector2 matches.

https://angular.io/api/core/Directive#selector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM