Mark Timothy
Mark Timothy

Reputation: 1814

*ngIf for html attribute in Angular2

<ion-navbar  hideBackButton >
  <ion-title> </ion-title>
  ...
  ...

I want hideBackButton to be there conditionally and I don't want to repeat the whole ion-navbar element with *ngIf. Is it possible to to apply *ngIf for hideBackButton attribute?

Upvotes: 31

Views: 38948

Answers (3)

nricciardi
nricciardi

Reputation: 11

I'm resolving this problem using this approach:


<button class="btn"
          aria-expanded="false"

          #btnId
          (click)="log(btnId.attributes.getNamedItem('aria-expanded')?.value)"
          >

    Button click
</button>

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657198

You have to provide null to boolean values for them to get removed,

<ion-navbar [attr.hideBackButton]="someExpression ? true : null">

otherwise angular creates

<ion-navbar hideBackButton="false">

Upvotes: 46

Thierry Templier
Thierry Templier

Reputation: 202156

You can leverage interpolation:

<ion-navbar [attr.hideBackButton]="someExpression">
  <ion-title> </ion-title>
  ...
...

If someExpression is null the attribute won't be present and if someExpression is an empty string, the attribute will be there. Here is a sample:

@Component({
  selector: 'my-app',
  template: `
    <div [attr.hideBackButton]="someExpression">
      Test
    </div>
    <div (click)="toggleAttribute()">Toggle</div>
  `
})
export class AppComponent {
  constructor() {
    this.someExpression = null;
  }

  toggleAttribute() {
    if (this.someExpression==null) {
      this.someExpression = '';
    } else {
      this.someExpression = null;
    }
  }
}

See this plunkr: https://plnkr.co/edit/LL012UVBZ421iPX4H59p?p=preview

Upvotes: 22

Related Questions