Home >Web Front-end >JS Tutorial >A brief analysis of custom structural/attribute directives in Angular
Angular instructions are divided into three types, component (with template instructions), structural instructions (changing the host document structure), and attribute instructions (changing the host behavior). The following mainly introduces custom structural instructions and custom attribute instructions. .
1. Custom structural directives
Only one structural directive can be placed on an element , the written form of the structural instruction is * instruction name, * is a syntax sugar, the following code:
<div *ngIf=""></div> <!-- 等价于 --> <ng-template [ngIf]=""> <div></div> </ng-template>
The following is a customized structural instruction. When superadmin and admin are entered into the instruction, the DOM node is displayed, otherwise Remove node. [Related tutorial recommendations: "angular tutorial"]
@Directive({ selector: '[appLogin]' }) export class LoginDirective implements OnInit{ @Input('appLogin') user="" constructor(private VCR: ViewContainerRef,private TPL: TemplateRef<any>) { //在指令的构造函数中将 TemplateRef 和 ViewContainerRef 注入成私有变量。 } ngOnInit(){ if(this.user=='superadmin'||this.user=="admin"){ this.VCR.createEmbeddedView(this.TPL) }else{ this.VCR.clear() } } }
<div *appLogin="'superadmin'">超级管理员</div> <div *appLogin="'admin'">管理员</div> <div *appLogin="'user'">普通会员</div>
Effect:
2. Custom attribute instructions
Using attribute directives, you can change the appearance or behavior of DOM elements and Angular components.
1. Import ElementRef from @angular/core. The nativeElement property of ElementRef provides direct access to the host DOM element.
2. Add ElementRef in the directive's constructor() to inject a reference to the host DOM element, which is the target of appColor.
3. Add logic to the ColorDirective class. Under different input conditions, the background will be displayed as red, green, and blue respectively.
@Directive({ selector: '[appColor]' }) export class ColorDirective implements OnInit{ @Input() appColor="" constructor(private ele:ElementRef) { } ngOnInit(){ if (this.appColor == 'superadmin'){ this.ele.nativeElement.style.backgroundColor="red" } else if (this.appColor == 'admin') { this.ele.nativeElement.style.backgroundColor = "green" }else{ this.ele.nativeElement.style.backgroundColor = "blue" } } }rrree
Effect:
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of A brief analysis of custom structural/attribute directives in Angular. For more information, please follow other related articles on the PHP Chinese website!