本文介绍了Angular-mat-tab中的动态组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mat-tab-group(角度材料),我希望能够从mat-tabs后面的代码(包括其他组件)中添加代码.我正在使用ComponentFactoryResolver创建组件,但无法通过ViewContainerRef

I have a mat-tab-group (angular material) and I want to be able to add from code behind mat-tabs including other components. I am using ComponentFactoryResolver to create the component but I am not able to add the new component to the new mat-tab through the ViewContainerRef

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);
}

推荐答案

想要分享我的想法,以防其他人遇到问题:

Wanted to share what I came up with, in case it helps anyone else:

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中的动态组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:29