gpt4 book ai didi

javascript - 单击按钮在 ngfor 中加载多个组件

转载 作者:行者123 更新时间:2023-12-02 21:50:15 24 4
gpt4 key购买 nike

我正在使用 Angular-Material 创建一个项目。我想将 Accordion 面板集成到我的项目中。我在扩展面板内加载动态组件时遇到问题。我想根据条件在扩展面板内加载动态不同类型的组件。这是代码:

import {Component, NgModule, QueryList,ViewChildren, ComponentFactoryResolver, ViewContainerRef, TemplateRef, ViewEncapsulation}
from '@angular/core'
import { TcpModuleComponent } from './tcp-module/tcp-module.component'
import { UdpComponent } from './udp/udp.component'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
ref:any;
viewContainerRef = [];
@ViewChildren('target', {read: ViewContainerRef}) container: QueryList<ViewContainerRef>

constructor(private resolver: ComponentFactoryResolver) {}

category = [{
"type":"TCP&UDP Port",
"code":"port",
"locked":false
},
{
"type":"DHCP",
"code":"dhcp",
"locked":true
},
{
"type":"ALG",
"code":"alg"
},
{
"type":"Tracert",
"code":"tracert"
},
{
"type":"Bandwidth",
"code":"bandwidth"
},
];
panelOpenState: boolean = false;
allExpandState = false;
ngOnInit() {
console.log(this.category)
}
loadComponent(type,item,comp){
if(item.locked == true){
type._toggle();
return
}

let componentRef;
let componentFactory;


if(item.code == "port"){
this.container.toArray().map((viewContainerRef, i) => {
componentFactory = this.resolver.resolveComponentFactory(TcpModuleComponent);
componentRef = viewContainerRef.createComponent(componentFactory);
this.ref = componentRef;
// this.viewContainerRef.push(viewContainerRef)
return
});
}
if(item.code == "dhcp"){
this.container.toArray().map((viewContainerRef, i) => {
componentFactory = this.resolver.resolveComponentFactory(UdpComponent);
componentRef = viewContainerRef.createComponent(componentFactory);
this.ref = componentRef
return
});
}


}
}

Html部分

<mat-accordion >
<mat-expansion-panel *ngFor="let data of category" (click)="loadComponent(panelH,data)">
<mat-expansion-panel-header #panelH >
<mat-panel-title>
<span class="title">{{data.type}}</span>
</mat-panel-title>
</mat-expansion-panel-header>
<div *ngIf="data.code == 'port'">
<ng-container #target></ng-container>
</div>
</mat-expansion-panel>
</mat-accordion >

我没有得到正确的想法如何实现这一目标。

最佳答案

您可以直接向 html 添加组件标签,而不是添加 ng-container。

<mat-accordion >
<mat-expansion-panel *ngFor="let data of category" (click)="loadComponent(panelH,data)">
<mat-expansion-panel-header #panelH >
<mat-panel-title>
<span class="title">{{data.type}}</span>
</mat-panel-title>
</mat-expansion-panel-header>
<TcpModuleComponent *ngIf="data.code === 'port'"></TcpModuleComponent>
<UdpComponent*ngIf="data.code === 'dhcp'"></UdpComponent>
</mat-expansion-panel>
</mat-accordion >

关于javascript - 单击按钮在 ngfor 中加载多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60146718/

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