微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/angularjs/145992.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐