我想创建一个布局组件来安排项目组,例如:
<garden-bed>
<div #veg (click)="pluck()">carrot</div>
<div #veg (click)="pluck()">cabbage</div>
<div #veg (click)="pluck()">turnip</div>
</garden-bed>
到目前为止,该组件看起来像
@Component({
selector: 'app-garden-bed',
templateUrl: './garden-bed.component.html',
})
export class GardenBed {
@ContentChildren('veg') vegs: QueryList<ElementRef>;
constructor() { }
ngAfterViewInit() {
console.log('this.vegs=' + JSON.stringify(this.vegs));
}
}
但我无法弄清楚如何在模板中植入它们(garden-bed.component.html):
<div *ngFor="let veg of vegs">
<ng-content/ng-template *something="veg"></ng-template>
but this doesn't work.
veg should appear here and all its binding should work!
</div>
任何帮助都非常感谢!
答案 0 :(得分:0)
为了避免更改检测问题,您应该仅使用QueryList
从toArray
获取templateRef:
templates: TemplateRef[];
ngAfterViewInit() {
console.log('this.vegs=' + JSON.stringify(this.vegs));
this.templates = this.vegs.toArray();
}
然后使用ngTemplateOutlet
标记模板
<div *ngFor="let veg of templates">
<ng-container *ngTemplateOutlet="veg"></ng-container>
but this doesn't work.
veg should appear here and all its binding should work!
</div>
ngTemplateOutlet
还允许传递可以绑定到模板中的上下文数据
另见
不要被<ng-template [ngTemplateOutlet]="myTemplate"
弄糊涂,它只是我上面展示的替代语法