结构指令经过添加和删除 DOM 元素来更改 DOM 布局。Angular 中两个常见的结构指令是 *ngIf
和 *ngFor
。html
*
号语法*
号是语法糖,用于避免使用复杂的语法。咱们以 *ngIf
指令为例:typescript
(图片来源:https://netbasal.com/)浏览器
Angular 把 host (宿主元素) 包装在 template
标签里面app
Angular 将 ngIf
转换为属性绑定 - [ngIf]布局
首先,让咱们了解如何建立一个结构指令。 接下来咱们将要实现一个简单的 ngIf
指令。this
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[myNgIf]'}) export class MyNgIfDirective { constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { } @Input() set myNgIf(condition: boolean) { if (condition) { this.viewContainer.createEmbeddedView(this.templateRef); } else { this.viewContainer.clear(); } } }
咱们能够按照如下方式使用咱们的指令:spa
<div *myNgIf=”condition”></div>
下面咱们来解释一下上面的代码。code
如名字所示,TemplateRef
用于表示模板的引用。htm
(图片来源:https://netbasal.com/)对象
正如上面介绍的,模板中包含了 DOM 元素,但若是要显示模板中定义的元素,咱们就须要定义一个插入模板中元素的地方。在 Angular 中,这个地方被称做容器,而 ViewContainerRef
用于表示容器的引用。那什么元素会做为容器呢?
Angular 将使用 comment
元素替换 template
元素,做为视图容器。
咱们来看一个具体的示例:
@Component({ selector: 'my-app', template: ` <div> <h2 *myNgIf="condition">Hello {{name}}</h2> <button (click)="condition = !condition">Click</button> </div> `, }) export class App { name: string; condition: boolean = false; constructor() { this.name = 'Angular2' } }
以上代码成功运行后,浏览器的显示内容以下:
(图片来源:https://netbasal.com/)
ViewContainerRef
对象提供了 createEmbeddedView()
方法,该方法接收 TemplateRef
对象做为参数,并将模板中的内容做为容器 (comment 元素) 的兄弟元素,插入到页面中。
如今,你已经了解如何建立结构指令,接下来让咱们看看两个具体的实例。
@Directive({selector: '[ifRole]'}) export class IfRoleDirective { user$ : Subscription; @Input("ifRole") roleName : string; constructor( private templateRef : TemplateRef<any>, private viewContainer : ViewContainerRef, private authService : AuthService ) {} ngOnInit() { this.user$ = this.authService.user .do(() => this.viewContainer.clear()) .filter(user => user.role === this.roleName) .subscribe(() => { this.viewContainer.createEmbeddedView(this.templateRef); }); } ngOnDestroy() { this.user$.unsubscribe(); } }
<div *ifRole="'admin'"> Only for Admin </div> <div *ifRole="'client'"> Only for Client </div> <div *ifRole="'editor'"> Only for Editor </div>
import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core'; @Directive({ selector: '[range]' }) export class RangeDirective { _range: number[]; @Input() set range(value: number) { this.vcr.clear(); this._range = this.generateRange(value[0], value[1]); this._range.forEach(num => { this.vcr.createEmbeddedView(this.tpl, { $implicit: num }); }); } constructor( private vcr: ViewContainerRef, private tpl: TemplateRef<any>) { } private generateRange(from: number, to: number): number[] { var numbers: number[] = []; for (let i = from; i <= to; i++) { numbers.push(i); } return numbers; } }
以上示例中,咱们在调用 createEmbeddedView()
方法时,设置了第二个参数 {$implicit: num}
。Angular 为咱们提供了 let
模板语法,容许在生成上下文时定义和传递上下文。
这将容许咱们引用 *range="[20,30]; let num"
模板中声明的变量。咱们使用 $implicit
名称,由于咱们不知道用户在使用这个指令时,会使用什么名字。
(图片来源:https://netbasal.com/)
<h1>Your age:</h1> <select> <ng-container *range="[18, 80]; let num"> <option [ngValue]="num">{{num}}</option> </ng-container> </select> <h1>Year:</h1> <select> <ng-container *range="[1998, 2016]; let num"> <option [ngValue]="num">{{num}}</option> </ng-container> </select>
以上代码成功运行后,浏览器的显示内容以下:
(图片来源:https://netbasal.com/)