ここにはNgComponentOutlet
の使用例があります。あなたは二つの成分があるとしましょう:
@Component({
selector: 'dynamic-component-one',
template: `<p>I'm the Component 1</p>`
})
export class FirstDynamicComponent {}
@Component({
selector: 'dynamic-component-two',
template: `<p>I'm the Component 2</p>`
})
export class SecondDynamicComponent {}
以下のコンポーネントはデフォルトでFirstDynamicComponent
をロードしていますが、ボタンをクリックした場合SecondDynamicComponent
に置き換え:
@Component({
selector: 'my-app',
template: `
<button (click)="switchComponents()">Swith Components:</button>
<ng-container *ngComponentOutlet="content"></ng-container>
`
})
export class AppComponent {
comp1 = FirstDynamicComponent;
comp2 = SecondDynamicComponent;
content = this.comp1;
switchComponents() {
this.content = this.comp2;
}
}
は、動的コンポーネントの両方を登録することを忘れないでください。
@NgModule({
imports: [...],
declarations: [
AppComponent,
FirstDynamicComponent,
SecondDynamicComponent
],
entryComponents: [
FirstDynamicComponent,
SecondDynamicComponent
]
})
export class AppModule { }
StackBlitz example
:そのモジュールの
entryComponents
セクションでこの時
ルック - > https://angular.io/guide/dynamic-component-loader –
あなたは 'ngSwitch'またはhttps://stackoverflow.com/questions/36325212/angular-2-dynamic-のようなものを使用することができますtabs-with-user-click-selected-components/36325468#36325468をクリックします。 https://angular.io/api/common/NgComponentOutlet –
NgComponentOutletも参照して、おかげでそれを行うための非常に滑らかな印象の方法です。 –