Angular 2显示和隐藏元素 [英] Angular 2 Show and Hide an element
问题描述
我在Angular 2中隐藏和显示依赖于布尔变量的元素时遇到问题.
I'm having a problem hiding and showing an element depending of a boolean variable in Angular 2.
这是div显示和隐藏的代码:
this is the code for the div to show and hide:
<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
该变量已被编辑",并存储在我的组件中:
the variable is "edited" and it's stored in my component:
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,该元素也不会隐藏.为什么?
The element is hidden, when saveTodos function starts, the element is shown, but after 3 seconds, even if the variable come back to be false, the element does not hide. Why?
推荐答案
您应使用* ngIf指令
You should use the *ngIf Directive
<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回调内部时,缺少对外部作用域的引用.
Update: you are missing the reference to the outer scope when you are inside the Timeout callback.
所以像我在上面添加的那样添加.bind(this)
so add the .bind(this) like I added Above
Q:已编辑是全局变量.您在* ngFor循环中的处理方式是什么? –布劳恩
Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn
A:我会将edit作为属性添加到要迭代的对象上.
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
},
{
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);
}
}
这篇关于Angular 2显示和隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!