evayly
evayly

Reputation: 850

Can angular templates be variable?

I have a variable that is declared in my component, lets call it "myVar". Depending on this variable I want to display a certain ng-template. Here is an example component-template:

<div *ngIf="myVar; then myVar; else nothing"></div>
<ng-template #foo>My Foo-Content</ng-template>
<ng-template #nothing>No Content</ng-template>

Any possibility to make this work? I want "myVar" to be null or the name "foo", but this code above doesnt evaluate "myVar", of course.

Or is there any way around this? In my real application I have about 10 different values for "myVar", but the content is not really enough to make it an own component.

Do I have to make 10 different *ngIf's for this? :(

Upvotes: 0

Views: 35

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

NgSwitch seems like what you're looking for.

    <div [ngSwitch]="myVar">
      <div *ngSwitchCase="'Foo'">
        Content
      </div>
      <div *ngSwitchCase="'Bar'">
        Content
      </div>
      <div *ngSwitchDefault>
        Empty or fallback
      </div>
    </div>

Upvotes: 1

Related Questions