Javascript 角度动态注入特定组件
我有3个组件,我想根据从Get请求接收到的值将其中一个组件注入另一个html组件: Comp1,Comp2,Comp3 目前的方法并不理想,尤其是当3个组件可能很快变成20个组件时Javascript 角度动态注入特定组件,javascript,angular,Javascript,Angular,我有3个组件,我想根据从Get请求接收到的值将其中一个组件注入另一个html组件: Comp1,Comp2,Comp3 目前的方法并不理想,尤其是当3个组件可能很快变成20个组件时 <Comp1 *ngIf="data.value === 'comp_1'"></Comp1> <Comp2 *ngIf="data.value === 'comp_2'"></Comp2> <Comp3 *ngIf="data.value === '
<Comp1 *ngIf="data.value === 'comp_1'"></Comp1>
<Comp2 *ngIf="data.value === 'comp_2'"></Comp2>
<Comp3 *ngIf="data.value === 'comp_3'"></Comp3>
使用React,我可以通过函数调用轻松地注入JSX片段,但我不确定在Angular中这样做的最佳实践是什么。假设您有两个组件:
@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 {}
不要忘记在其模块的entryComponents
部分中注册这两个动态组件:
@NgModule({
imports: [...],
declarations: [
AppComponent,
FirstDynamicComponent,
SecondDynamicComponent
],
entryComponents: [
FirstDynamicComponent,
SecondDynamicComponent
]
})
export class AppModule { }
以下是
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 {}
不要忘记在其模块的entryComponents
部分中注册这两个动态组件:
@NgModule({
imports: [...],
declarations: [
AppComponent,
FirstDynamicComponent,
SecondDynamicComponent
],
entryComponents: [
FirstDynamicComponent,
SecondDynamicComponent
]
})
export class AppModule { }
看看这个->你可以使用
ngSwitch
或类似的工具。另请参见NgComponentOutlet,这是一种更简洁的方法,谢谢。请看此->您可以使用ngSwitch
或类似的方法。另请参见NgComponentOutlet,这是一种更简洁的方法,谢谢。