问题描述
我正在尝试一本书中的教程并收到错误:“无法从 html 中读取属性 'name' of undefined”。
这是 iterator.directive.ts 中的代码:
import { Directive,Input,TemplateRef,ViewContainerRef } 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 $implict: any) {}
}
这是html:
<div class="row m-2">
<div class="checkBox">
<label>
<input type="checkBox" [(ngModel)]="showTable" />
Show Table
</label>
</div>
<table *paif="showTable" class="table table-sm table-bordered table-striped">
<thead>
<th></th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
</thead>
<tbody>
<ng-template [paForOf]="getProducts()" let-item>
<tr>
<td colspan="4">
{{item.name}}
</td>
</tr>
</ng-template>
</tbody>
</table>
</div>
错误发生在 {{item.name}}。
这是我所做的分析:
在控制台中,在 iterator.directive.ts 行上,对于 (let i=0; i
这是调用堆栈:
core.js:6185 错误类型错误:无法读取未定义的属性“名称”
在 ProductComponent_table_5_ng_template_9_Template (template.html:18)
在 executeTemplate (core.js:11949)
在 refreshView (core.js:11796)
在 refreshDynamicEmbeddedViews (core.js:13154)
在 refreshView (core.js:11819)
在 refreshDynamicEmbeddedViews (core.js:13154)
在 refreshView (core.js:11819)
在 refreshComponent (core.js:13229)
在 refreshChildComponents (core.js:11527)
在 refreshView (core.js:11848)
解决方法
它发生了。
你打错了
class PaIteratorContext {
constructor(public $implict: any) {}
^^^^^^^^
}
应该是$implicit