Angular-mat-tab中的动态组件

时间:2018-09-25 13:02:01

标签: angular angular-material angular-dynamic-components

我有一个mat-tab-group(角度材料),我希望能够从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);
}

2 个答案:

答案 0 :(得分:3)

想分享我的想法,以防其他任何人

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>

答案 1 :(得分:0)

我还替换了BrowserAnimationsModule,而改用了NoopAnimationsModule。

docker run -it --security-opt seccomp=profile.json ubuntu:18.04 /bin/sh -c " chmod +x /etc/hosts"

chmod: changing permissions of '/etc/hosts': Operation not permitted

模板

docker run -it --security-opt seccomp=profile.json busybox /bin/sh -c " chmod +x /etc/host"
chmod: /etc/host: No such file or directory

模块

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