如何在Angular中渲染子组件的内容?

时间:2018-12-20 16:03:35

标签: angular typescript angular6 angular7 angular-template

我有3个组件,标签,标签和工具栏,其使用方式如下Online Example

<tabs>
  <tab title="tab 1" active="true">
    <toolbar>Toolbar 1</toolbar>
    Content 1
  </tab>
  <tab title="tab 2">
     <toolbar>Toolbar 2</toolbar>
     Content 2
  </tab>
</tabs>

因此选项卡上有很多选项卡,而选项卡上只有一个工具栏。

标签模板如下:

<div class="head">
  <ul class="tabs">
    <li *ngFor="let tab of tabs" (click)="select(tab)" class="tab" [class.active]="tab.active">
      <a>{{ tab.title }}</a>
    </li>
  </ul>

  <div class="toolbar">Toolbar of Active Tab</div>

</div>
<ng-content></ng-content>

如何在以下位置呈现当前活动选项卡的工具栏:

<div class="toolbar">Toolbar of Active Tab</div>

每个组件代码为:

export class TabsComponent implements AfterContentInit {    
  @ContentChildren(TabComponent) tabs: QueryList<TabComponent>;    
  select(tab: TabComponent) {
    this.tabs.toArray().forEach(tab => { 
      tab.active = false; 
    });
    tab.active = true;
  }
  ngAfterContentInit() {
    let actives = this.tabs.filter((tab) => tab.active);
    if(actives.length === 0) 
      this.select(this.tabs.first);
  }
}

export class TabComponent {
  @Input() active: boolean;
  @Input() title: string;
  @ContentChildren(ToolbarComponent) toolbar: ToolbarComponent;
}

export class ToolbarComponent { }

1 个答案:

答案 0 :(得分:0)

如我所见,最好的2种选择是:

选项1 :将工具栏与选项卡组件分开,并使用将道具设置到选项卡的相同方法设置其道具:

<div class="head">
  <ul class="tabs">
    <li *ngFor="let tab of tabs" (click)="select(tab)" class="tab" [class.active]="tab.active">
      <a>{{ tab.title }}</a>
      <div class="toolbar">Toolbar of Active Tab {{tab.toolbarTitle}}</div>
    </li>
  </ul>
</div>

选项2 :在AppState上传递工具栏道具,这样,工具栏将可以从任何地方访问它们。 https://ngrx.io/

相关问题