johnny 5
johnny 5

Reputation: 20987

Angular 2 Conditional attribute not working

I'm trying to create a conditional attribute in angular 2 I'm also using Ionic 2. I have an input in which I would like to control the (what I think is an attribute)

My code is working fine when I'm not trying to bind it conditionally:

<ion-label stacked color="primary">{{label}}</ion-label>

Now I changed my component to take in a new Input isStacked and I have a function to return the string if it is stack:

@Input() isStacked: boolean = true;
stackedDisplay(): string {
    return this.isStacked? "stacked" : '';
}

and I updated my Ion label to look like this:

<ion-label {{stackedDisplay()}} color="primary">{{label}}</ion-label>

When I do this I get an error:

Failed to execute 'setAttribute' on 'Element': '{{stackedDisplay()}}' is not a valid attribute name.

I looked at a few other questions on this and they say to use the attr binding:

<ion-label [attr.stacked]='isStacked' color="primary">{{label}}</ion-label>

when I do it this way the binding fails as well, can someone tell me how to conditionally bind this attribute?

Upvotes: 1

Views: 1062

Answers (2)

0mpurdy
0mpurdy

Reputation: 3353

Similarly to the answer @emil gave you could do

<ion-label stacked *ngIf="isStacked else notStacked" color="primary">{{label}}</ion-label>
<ng-template #notStacked>
  <ion-label color="primary">{{label}}</ion-label>
</ng-template>

(Inspiration from this answer documentation here)

And although it doesn't make sense to use it for a boolean value there is also ngSwitch

<div [ngSwitch]="stacked">
  <ion-label *ngSwitchCase="true" stacked color="primary">
  <ion-label *ngSwitchDefault color="primary">{{label}}</ion-label>
</div>

If you did not want to introduce an extra level of nesting in your output you could replace <div> with <ng-container>

Live plunker example

Upvotes: 1

emil
emil

Reputation: 6364

You can achieve it following way although it's not very beautiful.

<ion-label stacked *ngIf="isStacked" color="primary">{{label}}</ion-label>
<ion-label *ngIf="!isStacked" color="primary">{{label}}</ion-label>

Upvotes: 1

Related Questions