*Learning notes for Udemy course (Angular — The Complete Guide, Section 7 by Max)
Press enter or click to view image in full size
Directives and Components
Directives are ‘enhancements’ for elements.
They can change the configuration (properties, attributes), styling, or behaviour of elements.
Directives don’t have templates (this is the main differences with components — Components are Directives with a template).
Two types of Directives: Attribute Directive, Structural Directive
Attribute Directives
// Directives that changes attribute. <input type="email" name="email" [(ngModel)]="email" />
Structural Directives
shortand structural directives: e.g. *ngIf, *select’.
can only apply one structural directive per element when using the shorthand syntax.
<ng-container> can be used when to create wrapper layers when multiple structural directives need to be applied around the same physical DOM element or component, which allows the user to define the nested structure.
Get Siyu’s stories in your inbox
Join Medium for free to get updates from this writer.
// Directives that changes DOM. <p *ngIf="isActive">Show this line when the status is active.</p>
// np-template by default is not rendered, it would render when appAuth is user in the following example // Structural Directive and Syntactic Sugar can be used interchangeably <ng-template appAuth="user"> <p>Welcome!</p> </ng-template>
// alternative <p *appAuth="user">Welcome!</p>
Build-in Directives and Custom Directives
Build-in Directives
When using ngModel in Forms, in dev-tool, we can see classes with ‘ng’ prefiexes added to this element.
// ngModel here is a build-in directive <input name="title" ngModel />
// ngModel can be used with two-way binding <input type="email" name="email" [(ngModel)]="email" />
Custom Directives
We can create custom attribute directives, and custom structural directives.
Custom directives are way less than components been used in a project.
Custom Directives Example (highlight content on mouse hover)
create custom directive file
// highlight.directive.ts
import { Directive, ElementRef, inject } from '@angular/core';
2. import created directive in component ts file, and implement in the target code section
import {Component, input} from '@angular/core'; import { Movie } from '../model/movie.model'; import { HighlightDirective } from "../highlight.directive"; //import custom directive