加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – Angular 2显示和隐藏元素

发布时间:2020-12-17 08:44:03 所属栏目:安全 来源:网络整理
导读:我有一个问题隐藏和显示一个元素取决于一个布尔变量在Angular 2。 这是div的代码显示和隐藏: div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert" strongList Saved!/strong Your changes has been saved./div
我有一个问题隐藏和显示一个元素取决于一个布尔变量在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);
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读