javascript - 在 Angular 中 createEmbeddedView() 的 context 參數是什麼
我想知道在 Angular 的 createEmbeddedView() 方法中,context 參數的用途。線上的 Angular 文件沒有提供這個資訊。
例如,我正在閱讀這段程式碼,作者在其中製作了一個迭代器結構指令。
import {
Directive, ViewContainerRef, TemplateRef, Input, SimpleChange
} from "@angular/core";
@Directive({
selector: "[paForOf]"
})
export class PaIteratorDirective {
constructor(private container: ViewContainerRef, private template: TemplateRef<Object>) {
}
@Input("paForOf") dataSource: any;
ngOnInit() {
this.container.clear();
for (let i = 0; i < this.dataSource.length; i++) {
this.container.createEmbeddedView(this.template, new PaIteratorContext(this.dataSource[i]));
}
}
}
class PaIteratorContext {
constructor(public $implicit: any) { }
}
這會在範本的核取方塊被勾選事件中顯示,如下所示:
<div class="checkbox">
<label><input type="checkbox" [(ngModel)]="showTable" />Show Table</label>
</div>
<table *paIf="showTable" class="table table-sm table-bordered table-striped">
<tr>
<th></th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
</tr>
<template [paForOf]="getProducts()" let-item>
<tr>
<td colspan="4">{{item.name}}</td>
</tr>
</template>
</table>
我想理解這段程式碼:
this.container.createEmbeddedView(this.template, new PaIteratorContext(this.dataSource[i]));
為什麼我需要創建 PaIteratorContext() 類的對象?為什麼我不能直接這樣做:
this.container.createEmbeddedView(this.template, this.dataSource[i]);
請幫忙?
答案#1
當你定義一個模板時,你可以透過 let-paramname 指定輸入參數:
<template [paForOf]="getProducts()" let-item='item'>
<span>{{item.name}}</span>
</template>
當創建模板時,context 物件就是允許你將那些參數傳遞給模板的東西。
this.container.createEmbeddedView(this.template, {item: {name: 'John'}}`
為什麼我需要創建 PaIteratorContext() 類的物件?為什麼我不能直接這樣做:
你不必創建 PaIteratorContext 的實例,在那種特定情況下,你只需傳遞一個帶有 name 屬性的對象即可。因此以下方式也可以使用:
this.container.createEmbeddedView(this.template, { $implicit: this.dataSource[i] });
如果輸入屬性像這樣指定 let-item 而沒有第二部分 =something,嵌入視圖會將其視為 let-item=$implicit,所以你必須傳遞一個具有 $implicit 屬性的上下文物件。
