0

How to inject provider into container component in Angular2?

For example I have parent component:

@Component({
    selector: 'myForm',
    template: '<form><myForm-detail></myForm-detail></form>',
    directives: [ MyFormDetailComponent ]
})
export class MyFormComponent {
    ...
}

And container component:

@Component({
    selector: 'myForm-detail',
    template: '<input type="text">',
    providers: [ MyService ]
})
export class MyFormDetailComponent {
    constructor(s: MyService) {
        console.log(s); // return "undefined"
    }

    ...
}

How to inject MyService into MyFormDetailComponent?

Alexey Savchuk
  • 1,068
  • 6
  • 13
  • 26

1 Answers1

1

If you want to inject the same service into both component, you can simply define MyService into the providers attribute of the parent component. This way (and because of hierarchical injectors), you will be able to inject it into the two components:

@Component({
    selector: 'myForm',
    template: '<form><myForm-detail></myForm-detail></form>',
    directives: [ MyFormDetailComponent ],
    providers: [ MyService ]
})
export class MyFormComponent {
  constructor(s: MyService) {
  }
  ...
}

(...)

@Component({
    selector: 'myForm-detail',
    template: '<input type="text">',
})
export class MyFormDetailComponent {
  constructor(s: MyService) {
    console.log(s);
  }
}

See this plunkr: https://plnkr.co/edit/rUBgioLtqIAfWNCkRnlN?p=preview.

If you want to know more about hierarchical injectors, you could have a look at this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360