Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why directives selector is in `[]`

Tags:

angular

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>
like image 919
Manu Chadha Avatar asked Feb 14 '18 07:02

Manu Chadha


2 Answers

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.

like image 145
O. R. Mapper Avatar answered Sep 30 '22 16:09

O. R. Mapper


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

  1. element selector - you can create new html tag
  2. class selector - you can use this as class in HTML tags
  3. 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
like image 45
Prasanth S Avatar answered Sep 30 '22 16:09

Prasanth S