Difference between @Self and @Host Angular 2+ Dependency Injection Decorators

前端 未结 4 1390
忘了有多久
忘了有多久 2020-12-30 01:49

Kindly explain the difference between @Self and @Host.

The angular API documentation gives some idea. But it\'s not clear to me. The example provided for Self<

4条回答
  •  粉色の甜心
    2020-12-30 02:35

    https://netbasal.com/exploring-the-various-decorators-in-angular-b208875b207c

    Host:

    @Host — The @Host decorator tells DI to look for a dependency in any injector until it reaches the host

    Self:

    @Self — The @Self decorator tells DI to look for a dependency only from itself, so it will not walk up the tree

    here is an example:

    https://plnkr.co/edit/UmpPTnzcRxgDc9Hn5I9G?p=preview

    As you see MyDir directive use: @Self to access its own Car Its component' @Host Garage dependency @Optional @Host Sun dependency that is not defined on Host but defined on App. Since it is not defined on Host - it will be null

    Output will be:

     parent component. 
      { "type": "child garage", 
        "car": { "model": "child car" }, 
        "sun": null 
      }
    

    Here is components and providers:

      class Garage {
        car;
        type;
        sun;
    
        constructor(type) {
          this.type=type;
        }
        setCar(car) {
          this.car = car;
        }
        setSun(sun) {
          this.sun = sun;
        }
      }
    
      class Car {
        model;
        constructor(model) {
          this.model=model;
        }
      }
    
      class Sun { }
    
      @Directive({
        selector: '[myDir]',
        providers:[
          {provide: Car, useValue: new Car('child car')}
          {provide: Garage, useValue: new Garage('child garage')}
        ]
      })
      export class MyDir {
        constructor(@Self() private car: Car, @Host() private garage: Garage,
          @Optional() @Host() private sun: Sun) {
           this.garage.setCar(this.car);
           this.garage.setSun(this.sun);
        }
      }
    
      @Component({
        selector: 'parent',
        template: `
           parent component. {{garage|json}}
        `,
        providers:[
          {provide: Car, useValue: new Car('parent car')},
          {provide: Garage, useValue: new Garage('parent garage')}
        ]
      })
      export class Parent {
        childDep;
        constructor(private car: Car, private garage: Garage) {
        }
      }
    
      @Component({
        selector: 'my-app',
        template: `
      
        `,
        providers:[
          {provide: Car, useValue: new Car('app car')},
          {provide: Garage, useValue: new Garage('app garage')},
          {provide: Sun, useValue: 'sun'}
        ]
      })
      export class App {
      }
    

提交回复
热议问题