NgTemplateOutlet with dynamic value

I am using ngTemplateOutlet with a dynamic value.

<ng-container *ngFor="let part of objectKeys(config);"> <ng-container *ngIf="config[part]"> <ng-container [ngTemplateOutlet]="part"></ng-container> </ng-container> </ng-container> <ng-template #one></ng-template> <ng-template #two></ng-template> 
  • Where config is the object
  • Where config[part] is logical
  • Where part is the key of the object and the value passed to ngTemplateOutlet.

I always get the error:

 ERROR TypeError: templateRef.createEmbeddedView is not a function 

I watched: https://stackoverflow.com/a/318829/

But maybe I can't do something like this.

In fact, the config object contains a boolean, as I said, and defines a part of the displayed form.

This is really a great form and for better reading, I am looking for a solution to separate it.

UPDATE

The configuration object looks like this:

 config = { one: true, two: false } 

So, in my form only <ng-template #one></ng-template> displayed. If I return two to true, both will be displayed.

I do not know if this is the best approach. I can use * ngIf, but with this solution I have really unreadable big code.

+9
source share
1 answer

Add them to the component class.

 @ViewChild('one') one:TemplateRef<any>; @ViewChild('two') two:TemplateRef<any>; 

and get links to the template using

 <form no-validate (ngSubmit)="onSubmit(search)"> <ng-container *ngFor="let part of objectKeys(config);"> <ng-container *ngIf="config[part]"> <ng-container [ngTemplateOutlet]="this[part]"></ng-container> </ng-container> </ng-container> </form> 

Stackblitz example

+10
source

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


All Articles