将组件注入 ng-container? (从文件加载模板)

Injecting component to ng-container? (load ng-template from file)

我正在尝试在我的 Angular 应用程序中构建一个简单的选项卡菜单。

parant.component.html:

<div>
  <button (click)="selectTab(1)">Tab1</button>
  <button (click)="selectTab(2)">Tab2</button>

  <ng-container *ngTemplateOutlet="(selected == 1) ? template1 : template2">
  </ng-container>

  <ng-template #template1>I'm page 1</ng-template>
  <ng-template #template2>I'm page 2</ng-template>
</div>

parant.component.ts:

public selected = 1;
public selectTab(tabName) {
  this.selected = tabName;
}

只要 <ng-template> 是同一页面 html 的一部分,就可以正常工作。现在我的页面(#template1#template2 的内容)变得复杂,我想将它们移动到单独的组件中。

如何将组件注入 <ng-container>??

compnent-templet1 and compnent-templet2 is name of component which previously was in ng-templet now you put them in component*

 <ul>
            <li *ngFor='let link of links'>
                <ng-container 
                     [ngTemplateOutlet]="link.type == 'complex' ?complexLink : simpleLink" 
                     [ngTemplateOutletContext]="{link:link}">
                </ng-container>
            </li>
        </ul>

        <ng-template #simpleLink let-link='link'>
            Simple : {{ link.name }}
    <compnent-templet2 [input]="link.somevalue"></compnent-templet2>
        </ng-template>

        <ng-template #complexLink let-link='link'>
            Complex : {{ link.name }}
    <compnent-templet1 [input]="link.somevalue"></compnent-templet1>

要将组件注入 <ng-container>,您不需要使用 *ngTemplateOutlet,而是使用 *ngComponentOutlet

您可以在 NgComponentOutlet

查看完整的 API

tab1.component.html:

<p>tab1 works!</p>

tab2.component.html:

<p>tab2 works!</p>

parant.component.html:

<div>
  <button (click)="selectTab(1)">Tab1</button>
  <button (click)="selectTab(2)">Tab2</button>

  <ng-container *ngComponentOutlet="activeTab">
  </ng-container>
</div>

parant.component.ts:

import { Tab1Component } from './tab1.component';
import { Tab2Component } from './tab2.component';
...

public activeTab = Tab1Component;

public selectTab(tabName) {
  if (tabName == 1) {
    this.activeTab = Tab1Component ;
  }
  else if (tabName == 2) {
    this.activeTab = Tab2Component ;
  }  
}

并且不要忘记将这些动态组件添加到 entryComponents 部分。

app.module.ts:

import { Tab1Component } from './tab1.component';
import { Tab2Component } from './tab2.component';
...
@NgModule({
  ...
  entryComponents: [
    Tab1Component,
    Tab2Component,
    ...