0

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!

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.