Angular - mat-tab 中的动态组件

标签 angular angular-material angular-dynamic-components

我有一个 mat-tab-group ( Angular Material ),我希望能够从 mat-tabs 后面的代码添加,包括其他组件。我正在使用 ComponentFactoryResolver 创建组件,但无法通过 ViewContainerRef 将新组件添加到新的 mat-tab

html

<mat-tab-group>
 <mat-tab *ngFor="let tab of tabs"  [label]="tab.title">
  <div #test></div>
 </mat-tab>
</mat-tab-group>

隐藏代码

private open(type:string):void{
 var tab = {title:'test'};
 this.tabs.push(tab);

 const factory = this.componentFactoryResolver.resolveComponentFactory(DiscountGridComponent );
 //this will add it in the end of the view
 const newComponentRef = this.viewContainerRef.createComponent(factory);
}

最佳答案

想分享我的想法,以防对其他人有帮助:

export class DynamicTabComponent implements AfterViewInit {
    public tabs = [ComponentOne, ComponentTwo];

    @ViewChild('container', {read: ViewContainerRef, static: false}) public viewContainer: ViewContainerRef;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    }

    public ngAfterViewInit(): void {
        this.renderComponent(0);
    }

    public tabChange(index: number) {
        setTimeout(() => {
            this.renderComponent(index);
        });
    }

    private renderComponent(index: number) {
        const factory = this.componentFactoryResolver.resolveComponentFactory(this.components[index]);
        this.viewContainer.createComponent(factory);
    }
}

模板:

<mat-tab-group (selectedIndexChange)="tabChange($event)">
    <mat-tab label="Tab" *ngFor="let component of components">
        <ng-template matTabContent>
            <div #container></div>
        </ng-template>
    </mat-tab>
</mat-tab-group>

关于Angular - mat-tab 中的动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52498869/

相关文章:

angular - 如何一次关闭使用 Angular Material 打开的所有对话框模式

angular-material - Angular Material 中的样式 mat-radio-button

angular - 如何保持悬停时显示动态弹出窗口

angular - 在 Angular 8 中获取以前和当前的 URL

javascript - Angular 4 动态添加点击事件

javascript - 如何用 MatdialogRef 显示对话框?

angular - 如何以 Angular 动态删除组件

angular - 如何动态地将组件添加到服务中的另一个组件

angular - 如果 "ng serve"正在运行,站点不会自动重新加载

javascript - 指向外部 URL 的 Angular 2 链接被视为路由的相对路径