[英]Injecting component to ng-container? (load ng-template from file)
I'm trying to build a simple tabs-menu in my Angular app.我正在尝试在我的Angular应用程序中构建一个简单的选项卡菜单。
parant.component.html: parent.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: parent.component.ts:
public selected = 1;
public selectTab(tabName) {
this.selected = tabName;
}
This is working fine, as long as the <ng-template>
is part on the same page html.这工作正常,只要
<ng-template>
是同一页面 html 的一部分。 Now my pages (the content of #template1 and #template2 ) become complex and I want to move them to separate components.现在我的页面( #template1和#template2的内容)变得复杂,我想将它们移动到单独的组件。
How could I inject component into <ng-container>
??如何将组件注入
<ng-container>
?
To inject a Component into <ng-container>
, you didn't need to use *ngTemplateOutlet
, instead use *ngComponentOutlet
.要将 Component 注入
<ng-container>
,您不需要使用*ngTemplateOutlet
,而是使用*ngComponentOutlet
。
You can see the full API at: NgComponentOutlet您可以在以下位置查看完整的 API: NgComponentOutlet
tab1.component.html: tab1.component.html:
<p>tab1 works!</p>
tab2.component.html: tab2.component.html:
<p>tab2 works!</p>
parant.component.html: parent.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: parent.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 ;
}
}
And don't forget to add these dynamic components to the entryComponents
section.并且不要忘记将这些动态组件添加到
entryComponents
部分。
app.module.ts: app.module.ts:
import { Tab1Component } from './tab1.component';
import { Tab2Component } from './tab2.component';
...
@NgModule({
...
entryComponents: [
Tab1Component,
Tab2Component,
...
compnent-templet1 and compnent-templet2 is name of component which previously was in ng-templet now you put them in component*
compnent-templet1 和 compnent-templet2 是以前在 ng-templet 中的组件的名称,现在您将它们放在组件中*
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.