my-for.directive.ts
@Directive({
selector: '[appMyFor]'
})
export class MyForDirective implements OnInit, OnChanges {
@Input() appMyForOf: Array<any>;
constructor(private temRef: TemplateRef<any>, private viewRef: ViewContainerRef) { }
ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
for (const input of this.appMyForOf) {
this.viewRef.createEmbeddedView(this.temRef, {
$implicit: input,
index: this.appMyForOf.indexOf(input),
});
}
}
ngOnInit(): void {
}
}
我的观点如下:
d-test2.component.html
<p *appMyFor="let nr of numbers">
{{ nr }}
</p>
组件看起来像:
d-test2.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-d-test2',
templateUrl: './d-test2.component.html',
styleUrls: ['./d-test2.component.css']
})
export class DTest2Component implements OnInit {
constructor() { }
numbers = [1, 2, 3];
ngOnInit(): void {
}
}
所以这里的问题是d-test2.component.html中的段落元素没有在浏览器中呈现。在浏览器控制台中看到警告。