Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

angular - ngTemplateOutlet with dynamic value

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...