我可以扩展 angular 组件并在 ngFor 循环中引用基础组件吗?
Can I extend an angular component and reference the base component in an ngFor loop?
是否可以扩展 angular 中的组件?如果是这样,如果它们都扩展了相同的基本组件,我可以创建一个包含多个不同组件的列表(通过 ngFor 循环)吗?
例如,如果所有菜单项都扩展相同的 "CustomMenuItem" 组件,我的自定义菜单栏是否可以列出不同种类的菜单项?有些是下拉菜单,有些是按钮,有些是文本框等,但所有这些都共享一些基本功能...
@Component({
selector: 'custom-menu-bar',
inputs: ['customMenuItems'],
outputs: ['onMenuEvent'],
template: `
<div class="row">
<custom-menu-item *ngFor="#item of customMenuItems">
...
</custom-menu-item>
</div>
`
})
export class CustomMenuBar {
customMenuItems: CustomMenuItem[];
onMenuEvent: EventEmitter<MenuEvent>;
//...
}
您可以在 angular 2 中使用 DynamicComponentLoader 来完成。
https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html
下面是文档中的代码示例:
@Component({
selector: 'child-component',
template: 'Child'
})
class ChildComponent {
}
@Component({
selector: 'my-app',
template: 'Parent (<div #child></div>)'
})
class MyApp {
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
dcl.loadIntoLocation(ChildComponent, elementRef, 'child');
}
}
bootstrap(MyApp);
从 angular 2.3 开始,我们获得了组件继承 - 请查看以下示例代码(摘自 this blog post):
@Component({
selector: 'person',
template: `<h4>Person: {{name}}</h4>`
})
export class Person {
@Input() name: string;
}
@Component({
selector: 'employee',
template: `<h4>Employee: {{name}}, id: {{id}}</h4>`
})
export class Employee extends Person {
@Input() id: string;
}
<div>
<person name="John"></person>
<employee name="Tom" id="45231"></employee>
是否可以扩展 angular 中的组件?如果是这样,如果它们都扩展了相同的基本组件,我可以创建一个包含多个不同组件的列表(通过 ngFor 循环)吗?
例如,如果所有菜单项都扩展相同的 "CustomMenuItem" 组件,我的自定义菜单栏是否可以列出不同种类的菜单项?有些是下拉菜单,有些是按钮,有些是文本框等,但所有这些都共享一些基本功能...
@Component({
selector: 'custom-menu-bar',
inputs: ['customMenuItems'],
outputs: ['onMenuEvent'],
template: `
<div class="row">
<custom-menu-item *ngFor="#item of customMenuItems">
...
</custom-menu-item>
</div>
`
})
export class CustomMenuBar {
customMenuItems: CustomMenuItem[];
onMenuEvent: EventEmitter<MenuEvent>;
//...
}
您可以在 angular 2 中使用 DynamicComponentLoader 来完成。 https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html
下面是文档中的代码示例:
@Component({
selector: 'child-component',
template: 'Child'
})
class ChildComponent {
}
@Component({
selector: 'my-app',
template: 'Parent (<div #child></div>)'
})
class MyApp {
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
dcl.loadIntoLocation(ChildComponent, elementRef, 'child');
}
}
bootstrap(MyApp);
从 angular 2.3 开始,我们获得了组件继承 - 请查看以下示例代码(摘自 this blog post):
@Component({
selector: 'person',
template: `<h4>Person: {{name}}</h4>`
})
export class Person {
@Input() name: string;
}
@Component({
selector: 'employee',
template: `<h4>Employee: {{name}}, id: {{id}}</h4>`
})
export class Employee extends Person {
@Input() id: string;
}
<div>
<person name="John"></person>
<employee name="Tom" id="45231"></employee>