繁体   English   中英

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),
  ]
}) 

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

我可以想到的唯一无需编辑编译器功能的解决方案就是维护一个外部Injector并解析组件声明中的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM