正在向ng-container注入组件吗? (从文件加载ng-template) [英] Injecting component to ng-container? (load ng-template from file)

查看:119
本文介绍了正在向ng-container注入组件吗? (从文件加载ng-template)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 应用中构建一个简单的标签菜单.

I'm trying to build a simple tabs-menu in my Angular app.

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 的内容)变得很复杂,我想将它们移动到单独的组件中.

This is working fine, as long as the <ng-template> is part on the same page html. Now my pages (the content of #template1 and #template2) become complex and I want to move them to separate components.

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

How could I inject component into <ng-container>??

推荐答案

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

To inject a Component into <ng-container>, you didn't need to use *ngTemplateOutlet, instead use *ngComponentOutlet.

您可以在以下位置查看完整的API: NgComponentOutlet

You can see the full API at: NgComponentOutlet

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部分.

And don't forget to add these dynamic components to the entryComponents section.

app.module.ts:

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

这篇关于正在向ng-container注入组件吗? (从文件加载ng-template)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆