我想创建一个布局组件来排列项目组,例如:
<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
中获取 templateRefs使用toArray
仅一次:
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
还允许传递可以绑定(bind)到模板中的上下文数据
另请参阅
不要对 <ng-template [ngTemplateOutlet]="myTemplate"
感到困惑,这只是我上面展示的替代语法
关于javascript - 如何将 ElementRef 添加到本地 dom 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48828774/