Angular2 将组件注入其他组件
Angular2 Inject components into other components
我正在弄乱 Angular2,我希望能够基于引导绑定将一个组件注入另一个组件。
class HelloComponent {
name: string;
}
@Component({
selector: 'hello'
}
@View({
template: `<h3>Hello {{ name }}</h3>`
})
class HelloBobComponent extends HelloComponent {
constructor() {
this.name = 'Bob';
}
}
@Component({
selector: 'app'
}
@View({
directives: [HelloComponent]
template: `<h1>Welcome to my Angular2 app</h1>
<hello></hello>`
}
class AppComponent {
}
bootstrap(AppComponent, [
bind(HelloComponent).toClass(HelloBobComponent)
]);
这里我使用 HelloComponent 作为我希望 Angular2 的 Injector 解析 HelloBobComponent 的标记。我这样做是为了可以根据当前的应用程序配置将组件换入和换出。上面的例子显然行不通。这可能使用框架装饰器之一吗?我尚未通过博客或来源找到答案。
编辑:为了澄清,我如何在 View 装饰器上获取指令 属性 以将 HelloComponent 视为 di 标记而不是类型。
从 alpha37 开始,目前不支持此功能。编译器通过类型或绑定解析在 View 装饰器中传递的指令,但不从父注入器查找。
例如:
@View({
url: '...',
directives: [
Directive1,
bind(Directive2).toClass(Directive2Impl),
]
})
这里 "directives" 属性 的目的只是为了防止选择器命名冲突。后来添加了绑定支持以帮助测试。
在不编辑编译器函数的情况下,我能想到的唯一解决方案是维护一个外部注入器并解析组件声明的类型。
我正在弄乱 Angular2,我希望能够基于引导绑定将一个组件注入另一个组件。
class HelloComponent {
name: string;
}
@Component({
selector: 'hello'
}
@View({
template: `<h3>Hello {{ name }}</h3>`
})
class HelloBobComponent extends HelloComponent {
constructor() {
this.name = 'Bob';
}
}
@Component({
selector: 'app'
}
@View({
directives: [HelloComponent]
template: `<h1>Welcome to my Angular2 app</h1>
<hello></hello>`
}
class AppComponent {
}
bootstrap(AppComponent, [
bind(HelloComponent).toClass(HelloBobComponent)
]);
这里我使用 HelloComponent 作为我希望 Angular2 的 Injector 解析 HelloBobComponent 的标记。我这样做是为了可以根据当前的应用程序配置将组件换入和换出。上面的例子显然行不通。这可能使用框架装饰器之一吗?我尚未通过博客或来源找到答案。
编辑:为了澄清,我如何在 View 装饰器上获取指令 属性 以将 HelloComponent 视为 di 标记而不是类型。
从 alpha37 开始,目前不支持此功能。编译器通过类型或绑定解析在 View 装饰器中传递的指令,但不从父注入器查找。
例如:
@View({
url: '...',
directives: [
Directive1,
bind(Directive2).toClass(Directive2Impl),
]
})
这里 "directives" 属性 的目的只是为了防止选择器命名冲突。后来添加了绑定支持以帮助测试。
在不编辑编译器函数的情况下,我能想到的唯一解决方案是维护一个外部注入器并解析组件声明的类型。