Angular2将组件注入其他组件

时间:2015-09-16 19:39:53

标签: dependency-injection angular

我正在搞乱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标记而不是类型。

1 个答案:

答案 0 :(得分:0)

目前不支持alpha37。编译器通过类型或绑定解析在View装饰器中传递的指令,但不从父注入器中查找。

例如:

@View({
  url: '...',
  directives: [
    Directive1,
    bind(Directive2).toClass(Directive2Impl),
  ]
}) 

这里“指令”属性的意图只是为了防止选择器命名冲突。后来添加了绑定支持以帮助测试。

在不编辑编译器功能的情况下,我能想到的唯一解决方案是维护外部Injector并解析组件声明中的类型。