Angular 2中app.components.ts无法读取第二个组件问题求助
问题分析与解决方案
嘿,我一眼就发现问题所在了——你**重复使用了同一个组件选择器my-app**来定义两个不同的组件!在Angular中,每个组件的选择器必须是唯一的,后定义的组件会直接覆盖前一个,这就是为什么你只能看到其中一个组件(最后注册的那个),另一个完全被忽略了。
正确的做法:用一个根组件同时引入两个子组件
你需要保留一个唯一的根组件,然后把DropdownComponent和TableComponent作为子组件,在根组件的模板中同时引用它们。
步骤1:定义两个独立的子组件
// 下拉列表组件 @Component({ selector: 'dropdown-fs', template: `<div>这里是下拉列表组件的内容</div>` }) export class DropdownComponent {} // 表格组件 @Component({ selector: 'table-fs', template: `<div>这里是表格组件的内容</div>` }) export class TableComponent {}
步骤2:定义唯一的根组件,引入两个子组件
@Component({ selector: 'my-app', // 唯一的根组件选择器 template: ` <dropdown-fs></dropdown-fs> <table-fs></table-fs> `, directives: [DropdownComponent, TableComponent] // 把两个子组件都加入指令列表 }) export class AppComponent {}
为什么原来的代码无效?
你连续两次使用selector: 'my-app',Angular无法识别两个同名的组件,最终只会加载最后一个被注册的组件(也就是带有<table-fs>的那个,具体取决于代码执行顺序),另一个组件的定义直接被覆盖了,自然不会显示。
内容的提问来源于stack exchange,提问作者TeeKay
相关产品推荐
相关产品推荐

