【问题标题】:Angular material tabs using ngComponentOutlet使用 ngComponentOutlet 的 Angular 材质选项卡
【发布时间】:2020-09-07 06:59:47
【问题描述】:

我正在使用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.

【问题讨论】:

  • 基本上您正在寻找一种通过*ngComponentOutlet 传递参数的方法,对吗? maybe this answer can help。它基本上说这是不支持的,你应该使用不是你想要的动态组件,所以我不知道我是否在帮助你。

标签: javascript angular typescript angular-material


【解决方案1】:

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

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

【讨论】:

  • @yurzui 你怎么知道把指令放在mat-tab 选择器上?出于某种原因,我认为该指令应该在包含*ngComponentOutlet 指令的ng-container 上,因为该组件被实例化到这个ng-container 中,非常想知道它是如何工作的。
  • NgComponentOutlet 指令默认查看 parentInjector github.com/angular/angular/blob/…
猜你喜欢
  • 1970-01-01
  • 2015-09-06
  • 2019-04-11
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多