How does @Host decorator work in injector tree

626 Views Asked by At

I'm trying to understand how the @Host decorator works uncoupled from view-components. So I created the following injector tree:

class Dependency {
}

@Injectable()
class NeedsDependency {
  constructor(@Host() public dependency: Dependency) {
    console.log(this.dependency); // outputs 'A', but I expected the error
  }
}

const parent = ReflectiveInjector.resolveAndCreate([{provide: Dependency, useValue: 'A'}]);
const child = parent.resolveAndCreateChild([]);
const grandchild = child.resolveAndCreateChild([NeedsDependency]);
grandchild.get(NeedsDependency);

I expected to get an error, because as I understand the host for grandchild injector is child, and there is no Dependency provided in the child injector. However, when I run this code, I get 'A' injected from the root injector. Why?

2

There are 2 best solutions below

5
Estus Flask On BEST ANSWER

Host doesn't have semantic meaning in the context of plain ReflectiveInjector.resolveAndCreate injector.

It is just ignored when being used outside the compiler.

For the desired behaviour,

I expected to get an error, because as I understand the host for grandchild injector is child, and there is no Dependency provided in the child injector.

consider using Self instead.

1
Günter Zöchbauer On

Specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component.

https://angular.io/docs/ts/latest/api/core/index/Host-decorator.html

Sounds to me it will look for providers and stop looking after it reached the injector of a component.