如何将 ElementRef 添加到本地 dom?
How to Add ElementRef into local dom?
我想创建一个布局组件来排列项目组,例如:
<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));
}
}
但我不知道如何将它们种植在模板中(花园-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>
非常感谢任何帮助!
为避免更改检测出现问题,您应该仅使用一次 toArray
从 QueryList
中获取 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
还允许传递可以在模板中绑定的上下文数据
另见
不要被 <ng-template [ngTemplateOutlet]="myTemplate"
搞糊涂了,它只是我上面显示的语法的替代语法
我想创建一个布局组件来排列项目组,例如:
<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));
}
}
但我不知道如何将它们种植在模板中(花园-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>
非常感谢任何帮助!
为避免更改检测出现问题,您应该仅使用一次 toArray
从 QueryList
中获取 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
还允许传递可以在模板中绑定的上下文数据
另见
不要被 <ng-template [ngTemplateOutlet]="myTemplate"
搞糊涂了,它只是我上面显示的语法的替代语法