typescript – Angular 2显示和隐藏元素

前端之家收集整理的这篇文章主要介绍了typescript – 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,元素也不会隐藏。为什么?

您应该使用* 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)就像我在上面添加

Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn

A : I would add edit as a property to the object I am iterating over.

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

猜你在找的Angularjs相关文章