* ngIf用于Angular2中的html属性 [英] *ngIf for html attribute in Angular2

查看:184
本文介绍了* ngIf用于Angular2中的html属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我希望hideBackButton有条件地出现,并且我不想使用* ngIf重复整个ion-navbar元素. 是否可以将* ngIf应用于hideBackButton属性?

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?

推荐答案

您可以利用插值:

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

如果someExpression为null,则该属性将不存在;如果someExpression为空字符串,则该属性将存在.这是一个示例:

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;
    }
  }
}

请参阅以下示例: https://plnkr.co/edit/LL012UVBZ421iPX4H59p?p=preview

这篇关于* ngIf用于Angular2中的html属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆