Angular directives that affect THE Dom layout or modify Dom properties.
Classification of Directive
Component
an extension of @Directive()
Demo
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'idata'. templateUrl: './user.component.html'. styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { constructor() {} ngOnInit(): void { } } Copy the code
- @Component is defined on the class
- TemplateUrl and template define view templates
@ Component source
export declare interface Component extends Directive {
changeDetection? : ChangeDetectionStrategy;
viewProviders? : Provider[]; moduleId? : string; templateUrl? : string; template? : string; styleUrls? : string[]; styles? : string[]; animations? : any[]; encapsulation? : ViewEncapsulation; interpolation? : [string, string]; entryComponents? : Array<Type<any> | any[]>; preserveWhitespaces? : boolean;} Copy the code
We can draw the following conclusions:
- Component is a special kind of directive
- Component The above attributes are optional
- What is the source code for Directive?
@ Directive source
export declare interface Directive {
selector? : string;
inputs? : string[]; outputs? : string[]; providers? : Provider[]; exportAs? : string; queries? : { [key: string]: any; }; host? : { [key: string]: string; }; jit? :true; } Copy the code
Attribute instructions
Attribute directives are used as attributes of elements
Built-in commands
- NgStyle
- NgClass
Custom instruction
- step 1:
# do not start with ng
ng generate directive highlight
Copy the code
- Code is as follows:
# src/app/highlight.directive.ts
import { Directive } from '@angular/core';
@Directive({
selector: '[appHighlight]'
}) export class HighlightDirective { constructor() {}} Copy the code
- Step 2: Add instruction processing logic
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective { constructor(el: ElementRef) { # Modify element background el.nativeElement.style.backgroundColor = 'yellow'; } } Copy the code
- Step3: declare the existence of instructions in the module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive'; @NgModule({ declarations: [ AppComponent, HighlightDirective Declare a reference to a directive in a view ]. imports: [ BrowserModule, AppRoutingModule, ]. providers: [], bootstrap: [AppComponent], exports: [] }) export class AppModule { } Copy the code
- Step 4: Apply instructions
<p appHighlight>Highlight me! </p>Copy the code
Structure of instruction
Structural directives are responsible for HTML layout
- Structure instructions that affect the current element as well as descendant elements
- Structure instructions, most of which begin with *
Built-in structure instruction
- ngIf
# false, do not render elements instead of hiding them after rendering
<div *ngIf="hero" class="name">{{hero.name}}</div>
Copy the code
- Why does ngIf false delete elements instead of hiding them? Here should be the frame designer for the pros and cons of choice! If the element is only hidden, then the element will remain in its original position, and the corresponding mouse event may still exist, which will affect the function of the existing component, the view rendering data. For details, please refer to the differences between visible,opacity and hiden in this article, which is well written!
- Angular compiles ngIf as follows:
<ng-template [ngIf]="hero"> <div class="name">{{hero.name}}</div> </ng-template> Copy the code
- ngFor
<div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd">
({{i}}) {{hero.name}}
</div>
Copy the code
- Angular compiles the following code:
<ng-template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
<div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</ng-template>
Copy the code
- ngSwitch
<div [ngSwitch]="hero? .emotion">
<app-happy-hero *ngSwitchCase="'happy'" [hero]="hero"></app-happy-hero>
<app-sad-hero *ngSwitchCase="'sad'" [hero]="hero"></app-sad-hero>
<app-confused-hero *ngSwitchCase="'confused'" [hero]="hero"></app-confused-hero>
<app-unknown-hero *ngSwitchDefault [hero]="hero"></app-unknown-hero>
</div> Copy the code
Custom structure instructions
- step 1:
ng generate directive appUnless Copy the code
- Code is as follows:
import { Directive } from '@angular/core'; @Directive({ selector: '[appUnless]' }) export class AppUnlessDirective { constructor() {} } Copy the code
- Step 2: Define element logic
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({
selector: '[appUnless]'
})
export class AppUnlessDirective { private hasView = false; constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { } @Input() set appUnless(condition: boolean) { if(! condition && ! this.hasView) { this.viewContainer.createEmbeddedView(this.templateRef); this.hasView = true; } else if (condition && this.hasView) { this.viewContainer.clear(); this.hasView = false; } } } Copy the code
- Step 3: Declare instructions
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive'; import { AppUnlessDirective } from './app-unless.directive'; @NgModule({ declarations: [ AppComponent, HighlightDirective, AppUnlessDirective Declare the structure directive ]. imports: [ BrowserModule, AppRoutingModule, ]. providers: [], bootstrap: [AppComponent], exports: [] }) export class AppModule { } Copy the code
- Step 4: Apply instructions
<p *appUnless="condition" class="unless a">
(A) This paragraph is displayed because the condition is false.
</p>
#ts
public condition = false; constructor(private domSanitizer: DomSanitizer){ interval(2000).subscribe(() => { this.condition = ! this.condition; }); } Copy the code