ngTemplateOutlet with dynamic value

2020-02-10 05:05发布

问题:

I'm using ngTemplateOutlet with 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 an object
  • Where config[part] is a boolean
  • Where part is the key of object and the value passed to ngTemplateOutlet.

I always get the error :

ERROR TypeError: templateRef.createEmbeddedView is not a function

I've followed : https://stackoverflow.com/a/41241329/5627096

But maybe I can't do something like that.

Actually the config object contains boolean, like I said, and define the part of a form to display.

It's really big form and for better reading, I'm looking for a solution to split it.

UPDATE

config object looks like :

config = {
    one: true,
    two: false
}

So in my form only the <ng-template #one></ng-template> is displayed. If I turn two to true, both are displayed.

I don't know if it's the best approach. I can use *ngIf but with this solution I have really unreadable big code.

回答1:

Add these to the components class

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

and get the template references 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



标签: angular