为什么@ViewChildren 只在第一次选择模板?
Why does @ViewChildren pick the template only for the first time?
我正在创建一个应用程序,我想在其中使用组件在 table 中呈现按钮。因此,我创建了一个组件,其中我保留了按钮模板并使用 @ViewChildren
获取模板并使用 ViewContainerRef
将组件应用于模板。但是,只有第一行得到设置,而不是其他行。我想不通这是什么原因?
这是我一直在尝试的:https://stackblitz.com/edit/angular-rsxvbt
无需使用 ComponentFactoryResolver 注入动态组件。您可以使用他的标签名称 <hello></hello>
来注入您的组件。我用一个有效的解决方案更新了你的 stackblitz:https://stackblitz.com/edit/angular-qbbewn
您的解决方案不起作用,因为您使用 @ViewChild
的单个引用,但您在 ng-For
中,因此您必须管理 QueryList
17=] 与 @ViewChildren
.
尝试按如下方式更改您的代码:
替换:
@ViewChild("dynamic", { static: false, read: ViewContainerRef }) ref;
@ViewChildren("dynamic") private button: QueryList<"dynamic">;
与:
@ViewChildren('dynamic', {read: ViewContainerRef}) public widgetTargets: QueryList<ViewContainerRef>;
这样我们就可以对每个 children.
有一个 ref
替换:
ngAfterViewInit() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(
HelloComponent
);
const ref = this.ref.createComponent(componentFactory);
}
与:
ngAfterViewInit() {
const targets = this.widgetTargets.toArray();
for (let i = 0; i < targets.length; i++) {
let target = targets[i];
if(target) {
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(HelloComponent);
let cmpRef: any = target.createComponent(componentFactory);
}
}
}
这样我们就可以循环我们的 refs 列表并动态创建我们的组件
祝一切顺利。
我正在创建一个应用程序,我想在其中使用组件在 table 中呈现按钮。因此,我创建了一个组件,其中我保留了按钮模板并使用 @ViewChildren
获取模板并使用 ViewContainerRef
将组件应用于模板。但是,只有第一行得到设置,而不是其他行。我想不通这是什么原因?
这是我一直在尝试的:https://stackblitz.com/edit/angular-rsxvbt
无需使用 ComponentFactoryResolver 注入动态组件。您可以使用他的标签名称 <hello></hello>
来注入您的组件。我用一个有效的解决方案更新了你的 stackblitz:https://stackblitz.com/edit/angular-qbbewn
您的解决方案不起作用,因为您使用 @ViewChild
的单个引用,但您在 ng-For
中,因此您必须管理 QueryList
17=] 与 @ViewChildren
.
尝试按如下方式更改您的代码:
替换:
@ViewChild("dynamic", { static: false, read: ViewContainerRef }) ref;
@ViewChildren("dynamic") private button: QueryList<"dynamic">;
与:
@ViewChildren('dynamic', {read: ViewContainerRef}) public widgetTargets: QueryList<ViewContainerRef>;
这样我们就可以对每个 children.
有一个 ref替换:
ngAfterViewInit() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(
HelloComponent
);
const ref = this.ref.createComponent(componentFactory);
}
与:
ngAfterViewInit() {
const targets = this.widgetTargets.toArray();
for (let i = 0; i < targets.length; i++) {
let target = targets[i];
if(target) {
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(HelloComponent);
let cmpRef: any = target.createComponent(componentFactory);
}
}
}
这样我们就可以循环我们的 refs 列表并动态创建我们的组件
祝一切顺利。