1

I'm trying to limit the search of my dependencies to only its host by using @Host.

But it's not working without ng-content or transclusion.

The below code is not working(without ng-content)

// Root Component
    @Component({
      selector: 'my-app',
      template: '<parent></parent>'
    })
    export class RootComponent { }


    @Component({
    selector: 'parent',
    template: '<child></child>',
    providers:[{provide:TestService,useClass:TestService}]

   })
   export class ParentComponent {
    name: string = '';
    constructor(abc:TestService){
        abc.name='SomeName';
        this.name=abc.name
       }
    }

    @Component({
    selector: 'child',
    template: '<h1>{{parent}}</h1>'
    })
         export class ChildComponent {
    parent: string = ""
    constructor(@Host() testService: TestService) {
        this.parent= 'My parent is :'+testService.name;
      }
    }

With ng-content Now just by changing the templates in RootComponent & the ParentComponent the above code starts working

 @Component({
      selector: 'my-app',
      template: '<parent><child></child></parent>'
    })
    export class RootComponent { }

 @Component({
    selector: 'parent',
    template: '<ng-content></ng-content>',
    providers:[{provide:TestService,useClass:TestService}]

   })
   export class ParentComponent {
    name: string = '';
    constructor(abc:TestService){
        abc.name='SomeName';
        this.name=abc.name
       }
    }

    @Component({
    selector: 'child',
    template: '<h1>{{parent}}</h1>'
    })
         export class ChildComponent {
    parent: string = ""
    constructor(@Host() testService: TestService) {
        this.parent= 'My parent is :'+testService.name;
      }
    }

Questions:

  1. Why the first code not working(without ng-content)..?
  2. @Host can only works with ng-content..?
  3. What difference ng-content makes as the structure of the compiled HTML is same in both the cases.

Here are the Plunker for reference:

Not working

Rishi Tiwari
  • 1,041
  • 1
  • 10
  • 20

1 Answers1

1

It looks like you need to use viewProviders instead of providers to work with @Host as also shown in @Host

Plunker example

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567