Angular part
2
Directives
Built In
Custom
Directives
• Directives are
classes that add additional behavior to elements in your Angular applications.
Use Angular's built-in directives to manage forms, lists, styles, and what
users see.
• Example
@component itself is a directive
• Two types
• Built in
Directives
• Custom
Directives
Builtin directives
• Also
called built-in structural directives
• NgClass—adds and
removes a set of CSS classes.
• NgStyle—adds and
removes a set of HTML styles.
• NgModel—adds
two-way data binding to an HTML form element.
• NgIf—conditionally
creates or disposes of subviews from the template.
• NgFor—repeat a
node for each item in a list.
• NgSwitch—a set of
directives that switch among alternative views.
NGIF
• Helps to
conditionally render elements
• Add or
remove an element by
• applying an
NgIf directive to a host element.
• <app-item-detail
*ngIf="isActive" [item]="item"></app-item-detail>
• Check nulls
• <div
*ngIf="currentCustomer">Hello,
{{currentCustomer.name}}</div>
NGFOR
• Use to Loop
through array elements ,render a list from an array property
• Define a block of
HTML that determines how Angular renders a single item.
• To list your
items, assign the short hand let item of items to *ngFor.
• <div
*ngFor="let item of items">{{item.name}}</div>
• Store each item
in the items array in the local item looping variable
• Make each item
available to the templated HTML for each iteration
• Translate
"let item of items" into an <ng-template> around the host
element
• Repeat the
<ng-template> for each item in the list
NGFOR2
• Get the index of
*ngFor in a template input variable and
• use it in the
template.
• <div
*ngFor="let item of items; let i=index">
• {{i + 1}} -
{{item.name}}</div>
• Reduce the number
of calls your application makes to the server by tracking changes to an item
list. With the *ngFor trackBy property, Angular can change and re-render only
those items that have changed, rather than reloading the entire list of items.
• method
• In this example,
the value to track is the item's id. If the browser has already rendered id,
Angular keeps track of it and doesn't re-query the server for the same id.
• trackByItems(index:
number, item: Item): number { return item.id; }
• <div
*ngFor="let item of items; trackBy: trackByItems">
• ({{item.id}})
{{item.name}}
• </div>
Ngclass
• Add or remove
multiple CSS classes simultaneously with ngClass.
• <div
[ngClass]="currentClasses">This div is initially saveable,
unchanged, and special.</div>
• Here ngclass is
calling a method which sets the classes
• Method
• currentClasses:
Record<string, boolean> = {};
• setCurrentClasses()
{ // CSS classes: added/removed per current state of component properties
• this.currentClasses
= { saveable: this.canSave, modified: !this.isUnchanged, special:
this.isSpecial };
NGstyle
• Use
NgStyle to set multiple inline styles simultaneously, based on the state of the
component.
• To
use NgStyle, add a method to the component class.
• In
the following example, setCurrentStyles() sets the property currentStyles with
an object that defines three styles, based on the state of three other
component properties.
• Method
• currentStyles:
Record<string, string> = {};
• setCurrentStyles()
{
• //
CSS styles: set per current state of component properties
• this.currentStyles
= {
• 'font-style': this.canSave ?
'italic' : 'normal',
• 'font-weight':
!this.isUnchanged ? 'bold' : 'normal',
• 'font-size': this.isSpecial ?
'24px' : '12px' };}
• Using
Ngstyle <div [ngStyle]="currentStyles"> This div is
initially italic, normal weight, and extra large (24px). </div>
Ngmodel => 2way property binding
• Use the NgModel
directive to display a data property and update that property when the user
makes changes.
• Define the
property
• @Input() property1
='test';
• add the ngmodel
directive
• This will add two
way binding
• <input
[(ngModel)]="property1" id="example-ngModel">
Ngswitch
• The
ngSwitch is an Angular directive, which allows us to display one or more DOM
elements based on some pre-defined condition.
• The
following is the syntax of ngSwitch. It contains three separate directives.
ngSwitch, ngSwitchCase & ngSwitchDefault.
• An
example switch ,this will basically be using num as property to store,and based
on the correct value that you in put in input field,will be passed to the
switch and finally the switchcase ,the corresponding “one” or “two”value will
be shown in ui
• Input string :
<input type='text' [(ngModel)]="num" />
•
• <div
[ngSwitch]="num">
• <div
*ngSwitchCase="'1'">One</div>
• <div
*ngSwitchCase="'2'">Two</div>
Custom Directive
• Custom
directive can be created by annotating a class a @Directive
• Look at the
appexample directive
• Usage in
html<button appExample defaultColor="red">Button</button>
• Import { HostListener, Directive, ElementRef, Renderer2, Input, OnInit } from '@angular/core'
•
@Directive({
• selector: '[appExample]',
• })
• export class ExampleDirective implements OnInit {
• @Input() defaultColor: string//
This makes the defaultColor variable changeable 2way binding
•
Adding events to custom directive
• Using
@HostListener annotation,more interactive logic can be added to the
directive. Decorator that declares a DOM event to listen for, and
provides a handler method to run when that event occurs.
• @HostListener('mouseenter') onMouseEnter() {
• this.setBgColor('yellow')
• }
•
@HostListener('mouseleave') onMouseLeave() {
• this.setBgColor('white')
• }
• This annotation
when added to the custom directive class ,will start listening to mouseevents
and fire the corresponding method
Custom directive
• Initially the
custom directive will make the button appear red,
• On mousenter it
will become yellow ,then when mouse is moved out
• The button
background color will become white
Custom Directive command
ng generate directive example app