简体   繁体   English

Angular2将组件注入其他组件

[英]Angular2 Inject components into other components

I'm messing around with Angular2 and I'm wanting the ability to inject one component into another based on the bootstrapped bindings. 我正在弄乱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)
]);

Here I'm using HelloComponent as a token that I want Angular2's Injector to resolve HelloBobComponent. 在这里,我将HelloComponent用作令牌,希望Angular2的Injector解析HelloBobComponent。 I'm doing this so that I can swap components in and out based on the current app configuration. 我这样做是为了可以根据当前应用程序配置来调入和调出组件。 The above example obviously doesn't work. 上面的示例显然不起作用。 Is this possible using one of the frameworks decorators? 使用框架装饰器之一可以做到这一点吗? I haven't found an answer yet digging though blogs or the source. 我还没有通过博客或源头找到答案。

edit: To clarify, how do I get the directives property on the View decorator to treat HelloComponent as a di token instead of a type. 编辑:澄清一下,如何获取View装饰器上的伪指令属性,将HelloComponent视为di令牌而不是类型。

This is currently not supported as of alpha37. 从alpha37开始,当前不支持此功能。 The compiler resolves directives passed in the View decorator by either type or binding but does not look up from the parent injector. 编译器通过类型或绑定解析在View装饰器中传递的指令,但不从父注入器查找。

For example: 例如:

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

The intention for the "directives" property here was only to prevent selector naming collision. 这里“指令”属性的目的只是为了防止选择器命名冲突。 Later bind support was added to aid in testing. 后来添加了绑定支持以帮助测试。

The only solution I can think of without editing the compiler function would be to maintain an external Injector and resolve types on component declaration. 我可以想到的唯一无需编辑编译器功能的解决方案就是维护一个外部Injector并解析组件声明中的类型。

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

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