Directives Flashcards
What is a Directive
It is a function that executes when Angular finds it in DOM
Examples of Directives
ngRepeat, ngIf, ngFor
Types of Directives
Structural and Attribute
Structural Directive
Create or destroy DOM elements
hide, show, enable, disable
ngIf, ngFor, ngSwitch
Attribute Directive
Change the state or behavior of DOM elements, component or another directive
ngClass - Add or remove several css classes simultaneously
ngStyle - set multiple inline styles simultaneously
ngModel - display data and update data when user makes changes
[ngClass]=”{‘blue’=true, ‘yellow’=false}” - Attribute Directive
Adds the class blue and removes class yellow if present. To add or remove a single class use class binding rather than ngClass [class.sale] = "onSale" like boolean/undefined/null [class]="classExpression" like string, object, array
{{show ? ‘hide’ : ‘show’}}
show = {{show}}
<br></br>
<div>Text to show</div>
It changes the structure of DOM tree and hence it is Structural Directive.
Custom Directive
First import {Directive, ElementRef} from ‘@angular/core’;
@Directive({
selector:’[my-error]’
})
export class MyErrorDirective{ constructor(elr:ElementRef){ elr.nativeElement.style.background='red'; } }
Now this directive can be used in any component
How is the custom directive used?
After creating the directive include it in app.module.ts file in @NgModule–> declarations
Can modules have their own attribute directives
Yes, RouteModule, FormModule has their own attribute directives.
[(ngModel)]
Two way data binding
It is part of FormsModule (include this in app component)
without ngModel example:
with ngModel example:
Useful site
https://www.sitepoint.com/practical-guide-angular-directives/
When to use ngStyle directive?
Most styles can be added simply to the HTML directly, for those we can simply add them to the class property, and no special Angular functionality is needed.
Many state styles can be used using browser-supported pseudo-class selectors such as :focus, we should prefer those conventional solutions for those cases.
For state styles that don’t have a pseudo-class selector linked to it, its best to go with ngClass.
If the ngClass expressions get too big, it’s a good idea to move the calculation of the styles to the component class.
Only for situations where we have a dynamically calculated embedded style should we use ngStyle, this should be rarely needed