gpt4 book ai didi

javascript - 如何为 *ngIf 内声明的模板调用 @ViewChild?

转载 作者:行者123 更新时间:2023-12-02 22:46:57 26 4
gpt4 key购买 nike

我正在表内动态调用组件。我正在使用 ViewContainerRef 在模板内动态渲染组件。但另一个元素内的模板并未被填充。也许是因为在声明 @ViewChild 时,另一个 ng-template 不在 DOM 中。

这是组件代码:

@ViewChild('loadComponent', {static: false, read: ViewContainerRef}) ref;


ngAfterViewChecked(): void {

const componentFactory =
this._componentFactoryResolver.resolveComponentFactory(DynamicComponent);
const ref = this.ref.createComponent(componentFactory);
ref.changeDetectorRef.detectChanges();
}

这是模板代码:

<table>
...
<tr *ngFor="let data of dataItems">

<td *ngIf="data.isDisplay">

<ng-template #loadComponent></ng-template> // this does'nt work

</td>

...

那么,一旦动态评估 td 代码,如何确保组件在 td 内呈现?

最佳答案

编辑:

通过非静态获取所有 templateRef,您可以迭代模板引用并为每个模板创建一个组件,之后您只需将其附加到某个 DOM 元素(templateRef 的父元素)

@ViewChildren("dynamicTemplateId") private refs: QueryList<"dynamic">;

this.refs.forEach((r: any) => {
// Create a new instance of the component
const dynamicComponentRef = componentFactory.create(this.injector);

// If you don't attach to appRef ng hook cycles won't work inside the component
// You can skip adding to application ref but you'll be needing to call .detectChanges() for every changes
this.appRef.attachView(dynamicComponentRef.hostView);

// Append to parentElement since templateRef isn't a element itself
r.elementRef.nativeElement.parentElement.appendChild(dynamicComponentRef.location.nativeElement);
});

这是一个有效的示例: https://stackblitz.com/edit/angular-gmnpku?file=src/app/app.component.ts

关于javascript - 如何为 *ngIf 内声明的模板调用 @ViewChild?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58357158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com