我有一个问题隐藏和显示一个元素取决于一个布尔变量在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指令
原文链接:https://www.f2er.com/angularjs/145992.html<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); } }