Angular 2显示和隐藏元素

新手上路,请多包涵

我在隐藏和显示取决于 Angular 2 中的布尔变量的元素时遇到问题。

这是 div 显示和隐藏的代码:

 <div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

该变量已“编辑”并存储在我的组件中:

 export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }, 3000);
  }
}

元素被隐藏,当 saveTodos 函数启动时,元素被显示,但 3 秒后,即使变量返回为 false,元素也不会隐藏。为什么?

原文由 user4956851 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 743
2 个回答

您应该使用 *ngIf 指令

<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}


更新:当您在 Timeout 回调中时,您缺少对外部范围的引用。

所以像我在上面添加的那样添加 .bind(this)

问:edited 是一个全局变量。您在 *ngFor 循环中的方法是什么? – 布劳亨

答:我会将编辑添加为我正在迭代的对象的属性。

 <div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

export class AppComponent implements OnInit{

  public listOfObjects = [
    {
       name : 'obj - 1',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    }
  ];
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

原文由 inoabrian 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 TS 文件中

showMyContainer: boolean = false;

在 HTML 中

<button (click)="showMyContainer=!showMyContainer">Show/Hide</button>

<div *ngIf="showMyContainer">
     your code
</div>

看我的 堆栈闪电战

很高兴听到有人得到帮助。

原文由 Pullat Junaid 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进