我对角度2世界有点新意,所以请原谅我这是一个天真的问题.
我想读一个json文件,其中包含我需要为页面显示的各种组件的元数据.
我需要读取这个json并按照它们在此处列出的顺序呈现子组件.
我已经成功使用了角度2提供的动态组件加载器API来动态加载for循环中的子组件.但是,还有一些其他要求使得使用此API有点复杂.
所以我正在寻找另一种方法来做同样的事情.这就像在父组件的ts文件中操作DOM一样,以按照JSON中提到的顺序获取子组件.
任何线索都会非常有帮助.
非常感谢!
PS:抱歉没有发布代码.我用我的手机发布了这个.
最佳答案 如果你不想使用DynamicComponentLoader(不赞成使用具有相同限制的ViewContainerRef.createComponent()),我只看到使用包装所有可能组件的元素并仅呈现所选组件的选项
@Component({
selector: 'wrapper-component',
directives: [Cmp1, Cmp2, Cmp3, ... Cmp10],
template: `
<div [ngSwitch]="type">
<cmp1 *ngSwitchCase="'cmp1'"></cmp1>
<cmp2 *ngSwitchCase="cmp2"></cmp2>
<cmp3 *ngSwitchCase="cmp3"></cmp3>
....
<cmp10 *ngSwitchCase="cmp4"></cmp4>
<div *ngSwitchDefault>not supported</div>
</div>
`})
export class WrapperComponent {
@Input() type:string;
}
并使用它
@Component({
selector: 'parent-cmp',
template: `
<wrapper-component *ngFor="let item of someJson" [type]="item.componentName"></wrapper-component>
`})
export class ParentComponent {
someJson; // assign the JSON here
}