【问题标题】:*ngIf for html attribute in Angular2*ngIf 用于 Angular2 中的 html 属性
【发布时间】:2016-03-07 10:20:41
【问题描述】:
<ion-navbar  hideBackButton >
  <ion-title> </ion-title>
  ...
  ...

我希望hideBackButton 有条件地存在,我不想用 *ngIf 重复整个 ion-navbar 元素。 是否可以将 *ngIf 应用于 hideBackButton 属性?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您必须为布尔值提供 null 才能删除它们,

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

    否则角度会创建

    <ion-navbar hideBackButton="false">
    

    【讨论】:

      【解决方案2】:

      您可以利用插值:

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

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

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

      看到这个 plunkr:https://plnkr.co/edit/LL012UVBZ421iPX4H59p?p=preview

      【讨论】:

      • 最初plunker链接初始化有问题。但现在效果很好。
      • 嗯,是的,我的示例 plunkr 有效;-) “示例有效”是什么意思?
      猜你喜欢
      • 2017-06-28
      • 1970-01-01
      • 2017-06-18
      • 2017-02-22
      • 2017-08-20
      • 1970-01-01
      • 2018-10-01
      • 2020-03-09
      • 2017-04-20
      相关资源
      最近更新 更多