I noticed that a Directive's selector is usually specified in []
but is used without the []
brackets. Why?
@Directive({
selector: '[appGoWild]'
})
export class GoWildDirective implements OnInit {
constructor(private renderer: Renderer2, private el: ElementRef) {}
ngOnInit() {
this.renderer.addClass(this.el.nativeElement, 'wild');
}
}
Usage in HTML
<h1 appGoWild>
Hello World!
</h1>
According to the docs:
It's the brackets (
[]
) that make it an attribute selector.
So, with brackets, the selector refers to an attribute and has to be written as you state:
<h1 appGoWild>
Without brackets, the selector would refer to an element:
<appGoWild>
In the aforementioned docs, you can find an example of that with the app-root
directive at the end of the article.
Hope you get a understanding from others answers, now am explaining a little about selector to get a clear view in this.
There are three types of selector
property selector - you can create new property in HTML
selector : 'your-option' // element selector
selector : '[your-option]' // property selector
selector : '.your-option' // class selector
To use this in HTML
<your-option></your-option> /* this is element selector usage
<div your-option></div> /* this is property selector usage
<div class="your-option"></div> /* this is class selector usage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With