Angular2将组件注入其他组件 [英] Angular2 Inject components into other components

查看:52
本文介绍了Angular2将组件注入其他组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在弄乱Angular2,并且希望能够基于自举绑定将一个组件注入另一个组件。

I'm messing around with Angular2 and I'm wanting the ability to inject one component into another based on the bootstrapped bindings.

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。这样做是为了我可以根据当前应用程序交换组件配置。上面的示例显然不起作用。是否可以使用框架装饰器之一?我还没有找到ans

Here I'm using HelloComponent as a token that I want Angular2's Injector to resolve 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.

编辑:澄清一下,我如何在View装饰器上获取指令属性,将HelloComponent视为di令牌而不是a令牌。类型。

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.

推荐答案

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

This is currently not supported as of 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({
  url: '...',
  directives: [
    Directive1,
    bind(Directive2).toClass(Directive2Impl),
  ]
}) 

The此处指令属性的目的只是为了防止选择器命名冲突。

The intention for the "directives" property here was only to prevent selector naming collision. Later bind support was added to aid in testing.

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

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.

这篇关于Angular2将组件注入其他组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆