Miron Foerster
Miron Foerster

Reputation: 21

Angular 16 docs: inject(ViewContainerRef) explanation

In the Angular docs' usage notes for ViewContainerRef I just don't get the statement inject(ViewContainerRef).

I'm pretty new to Angular and trying to find my way through the djungle of deprecated resources just to find the official docs inject something that in my understanding used to be only retrievable from a @viewChild.

I even tried implementing this approach but it won't work because I would have to provide ViewContainerRef in ngModule which in turn is not getting accepted by angular. Maybe because I'm not using standalone components? Or do I miss out on some fundamental angular concept? Please enlighten me!

Upvotes: 0

Views: 609

Answers (1)

serrulien
serrulien

Reputation: 725

With inject(ViewContainerRef) Your are injecting the view container reference of the host component.

@Component({
  selector: 'my-app',
  template: ""
})
export class AppComponent {
 constructor(private viewContainerRef: ViewContainerRef) {}
}

is equivalent to

@Component({
  selector: 'my-app',
  template: ""
})
export class AppComponent {
 viewContainerRef = inject(ViewContainerRef)
}

https://angular.io/api/core/inject

For an usage example you can look at the code of the NgIf directive which injects ViewContainerRef and use it to show/hide the content https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_if.ts

Upvotes: 0

Related Questions