yog*_*ing 6 javascript typescript angular
我想知道context参数createEmbeddedView()在 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) { }
}
Run Code Online (Sandbox Code Playgroud)
这显示在模板上的复选框选中事件中,如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
我想了解这段代码:
this.container.createEmbeddedView(this.template, new PaIteratorContext(this.dataSource[i]));
Run Code Online (Sandbox Code Playgroud)
为什么我需要创建 PaIteratorContext() 类的对象?为什么我不能这样做:
this.container.createEmbeddedView(this.template, this.dataSource[i]);
Run Code Online (Sandbox Code Playgroud)
请帮忙 ?
Max*_*kyi 11
定义模板时,您可以通过let-paramname以下方式指定输入参数:
<template [paForOf]="getProducts()" let-item='item'>
<span>{{item.name}}</span>
</template>
Run Code Online (Sandbox Code Playgroud)
上下文对象允许您在创建模板时将这些参数传递给模板。
this.container.createEmbeddedView(this.template, {item: {name: 'John'}}`
Run Code Online (Sandbox Code Playgroud)
为什么我需要创建 PaIteratorContext() 类的对象?为什么我不能这样做:
您不必创建 的实例PaIteratorContext,您只需name在该特定情况下传递具有该属性的对象。因此,以下内容也将起作用:
this.container.createEmbeddedView(this.template, { $implicit: this.dataSource[i] });
Run Code Online (Sandbox Code Playgroud)
如果输入属性是这样指定的,let-item而没有第二部分=something,则嵌入视图会将其视为let-item=$implicit您必须传递具有$implicit属性的上下文对象。
| 归档时间: |
|
| 查看次数: |
2808 次 |
| 最近记录: |