ANGULAR INTERVIEW QUESTION: What are the different kinds of Angular directives?
๐๐ก๐๐ซ๐ ๐๐ซ๐ ๐ญ๐ก๐ซ๐๐ ๐ค๐ข๐ง๐๐ฌ ๐จ๐ ๐๐ข๐ซ๐๐๐ญ๐ข๐ฏ๐๐ฌ:
๐๐๐ญ๐ญ๐ซ๐ข๐๐ฎ๐ญ๐ ๐๐ข๐ซ๐๐๐ญ๐ข๐ฏ๐๐ฌ
๐๐๐จ๐ฆ๐ฉ๐จ๐ง๐๐ง๐ญ๐ฌ
๐๐๐ญ๐ซ๐ฎ๐๐ญ๐ฎ๐ซ๐๐ฅ ๐๐ข๐ซ๐๐๐ญ๐ข๐ฏ๐๐ฌ
๐) ๐๐ก๐ ๐๐ญ๐ญ๐ซ๐ข๐๐ฎ๐ญ๐ ๐๐ข๐ซ๐๐๐ญ๐ข๐ฏ๐๐ฌ
They allow to modify the appearance and the behavior of a DOM element.
For example, ngStyle and ngClass.
You can make your own attribute directive.
Custom code:
import { Directive, ELementRef } from '@angular/core'; @Directive({ selector: '[appRedBackgroundColor]' }) export class RedBackgroundColorDirective { constructor (el:ElementRef){ el.nativeElement.style.backgroundColor = "red"l } }
Then you apply your custom directive on any DOM element or Angular component belonging to the same module:
<p appRedBackgroundColor>Hello World!</p>
๐) ๐๐ก๐ ๐๐จ๐ฆ๐ฉ๐จ๐ง๐๐ง๐ญ๐ฌ
The components are directives that have a binded template, style sheet and a selector property WITHOUT brackets.
selector: [appRedBackgroundColor] //Directives selector: appRedBackgroundColor //Components
๐) ๐๐ก๐ ๐ฌ๐ญ๐ซ๐ฎ๐๐ญ๐ฎ๐ซ๐๐ฅ ๐๐ข๐ซ๐๐๐ญ๐ข๐ฏ๐๐ฌ
Thes directives modify the DOM by adding orremoving elements or elements children.
The ngIf and ngFor are examples of structural directives:
<!-- *ngIf conditions the display --> <div *ngIf="age > 18"> ๐บ๐บ๐บ</div> <!-- *ngFor factorize the declarations of similar DOM elements--> <div *ngFor="let people of peopleList"> <p>{{ people.name }}</p> <p>{{ people.age }}</p> </div>
NB: the Angular structural directives have a star at the beginning of their selector.