使用ngComponentOutlet的角材料选项卡

时间:2020-05-20 19:13:16

标签: javascript angular typescript angular-material

我正在使用Angular Material Tabs浏览文档的不同部分。我已经在TabItem类中定义了每个标签,如下所示:

class TabItem {
     constructor(
         public component: Type<any>, 
         public data: TabData,
         public active: boolean
     ) {}
}

在视图中,我遍历每个TabItem并使用* ngComponentOutlet呈现每个TabItem的组件。

<mat-tab-group>
    <ng-container *ngFor="let tab of tabs">
        <mat-tab>
             <ng-template mat-tab-label>
                   <div class="mat-label-text" (click)="setActiveTab(tab)">{{ tab.data.label }}</div>
             </ng-template>

             <ng-container *ngComponentOutlet="tab.component"></ng-container>
        </mat-tab>
    </ng-container>
</mat-tab-group>

一切正常...除了我需要访问每个已解析组件中的当前TabItem来访问其ID,标签等。我遇到麻烦的原因是因为在线示例仅显示如何使用ngComponentOutlet作为动态组件。我的组件虽然没有动态变化,但是它们是固定的,但是是动态创建的。

我不知道如何使用注射器,因为我处于for循环中...除非我为每个单独的项目创建注射器。我也不想订阅每个组件中的服务……那简直太荒谬了。

Here is a stackblitz of what I am trying to accomplish.

1 个答案:

答案 0 :(得分:2)

您可以创建一条指令,将所需数据移植到您的组件中

data-provider.directive.ts

import { Directive, Input } from "@angular/core";

@Directive({
  selector: '[dataProvider]'
})
export class DataProviderDirective {
  @Input('dataProvider') data: any;
}

tabs.html

<ng-container *ngFor="let tab of tabs">
  <mat-tab [dataProvider]="tab">

现在,您动态生成的组件可以从该指令读取数据:

tab-one.component.ts

import { Component, OnInit } from '@angular/core';
import { DataProviderDirective } from './data-provider.directive';

@Component({
  selector: 'app-tab-one',
  template: `
    <p>I am tab one!</p>
    <p>How can I access my respective TabItem?</p>
    <pre>{{ dataProvider.data | json }}</pre> 
  `,
})
export class TabOneComponent implements OnInit {

  constructor(public dataProvider: DataProviderDirective) { }

  ngOnInit() {
    console.log(this.dataProvider.data)
  }
}

Forked Stackblitz