Bu...">

Why use ViewContainerRef over * ngif?

I could just do

<my-awesome-component *ngIf="ConditionToIncludeComponent"></my-awesome-component>

But each document on component insertion in dom is dynamically based on ViewContainerRef. I like what he does. But what makes it so special over * ngif?

Just indicate the pros and cons of both. You are welcome. Thank!

+4
source share
1 answer

TL; DR;

If you do not know which component will be used in the component template when building this template, use viewContainerRef. If you know the component in advance, but sometimes it can be hidden, use ngIf.

Explanation

viewContainerRef . ngIf html . , , , :

<my-awesome-component1 *ngIf="ConditionToIncludeComponent1"></my-awesome-component1>
<my-awesome-component2 *ngIf="ConditionToIncludeComponent2"></my-awesome-component2>
<my-awesome-component3 *ngIf="ConditionToIncludeComponent3"></my-awesome-component3>

viewContainerRef ( `ng-container). ngComponentOutlet, :

template: `<ng-container ngComponentOutlet="componentToInsert"></ng-container>`

class MyComponent {

   const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);

    if (ConditionToIncludeComponent1) {
        componentToInsert = myAwesomeComponent1;
    else if (ConditionToIncludeComponent2) {
        componentToInsert = myAwesomeComponent2;
    else if (ConditionToIncludeComponent3) {
        componentToInsert = myAwesomeComponent3;

createComponent:

template: `<ng-container #spot></ng-container>`

class MyComponent {
   @ViewChild('spot', {read: ViewContainerRef}) vc;

   const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);

    if (ConditionToIncludeComponent1) {
        vc.createComponent(myAwesomeComponent1);
    else if (ConditionToIncludeComponent2) {
        vc.createComponent(myAwesomeComponent2);
    else if (ConditionToIncludeComponent3) {
        vc.createComponent(myAwesomeComponent3);

html, ngIf - , ngIf .

:

+3

Source: https://habr.com/ru/post/1687241/


All Articles