我有一个问题隐藏和显示一个元素取决于一个布尔变量在Angular 2。
<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); } }
您应该使用* 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回调中时,缺少对外部作用域的引用。
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 举报,一经查实,本站将立刻删除。