我想创建一个布局组件来排列项目组,例如:
<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>
非常感谢您的帮助!
最佳答案
为避免更改检测出现问题,您应该仅使用一次QueryList
从toArray
中获取templateRefs:
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
还允许传递可以绑定到模板中的上下文数据也可以看看
What is let-* in Angular 2 templates?
不要被
<ng-template [ngTemplateOutlet]="myTemplate"
弄糊涂,它只是我上面显示的替代语法Empty context data of ng-template while implementing recursive ngFor loop