简体   繁体   中英

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.

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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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