簡體   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