[英]*ngIf on component class variable in angular2
我想在標志變量為true時顯示加載程序,並在標志為false時將其隱藏(雙向數據綁定),但是我不知道如何將* ngIf與組件變量一起使用
app.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from '../../models/users.model';
import { UserServices } from '../../services/User.service';
@Component({
selector: 'app-default',
templateUrl: './default.component.html',
styleUrls: ['./default.component.css']
})
export class defaultComponent implements OnInit {
public flag: boolean;
userList: User[];
constructor(private _service: UserServices) {
this.flag = true;
}
ngOnInit() {
this.getData();
}
getData() {
this.flag = true;
this._service.loadData().subscribe( response => { this.userList = response; });
this.flag = false;
}
}
default.component.html
<div *ngIf="flag == true" class="loader">Loading...</div>
<div class="content">
<!--my html-->
</div>
我只想在調用服務時顯示loader div,並在調用完成后隱藏它。
響應返回時,將標志設置為false。 否則,將立即將其設置為false:
getData() {
this.flag = true;
this._service.loadData().subscribe( response => {
this.userList = response;
this.flag = false;
});
}
另外,您不需要顯式檢查true
:
*ngIf="flag"
並且,如果願意,可以在聲明標志時對其進行初始化,而不用在構造函數中進行操作:
public flag: boolean = true;
移動this.flag = false;
進入subscribe
塊的。 由於javascript具有異步功能,因此在后端調用之前,您的flag
將設置為False。
並且簡單的ngIf條件會更好。
<div *ngIf="flag" class="loader">Loading...</div>
getData() {
this.flag = true;
this._service.loadData().subscribe( response => {
this.userList = response;
this.flag = false;
});
}
您的getData
需要一些工作:
getData() {
this.flag = true;
this._service.loadData().subscribe((response) => {
this.userList = response;
this.flag = false;
});
}
而且您的組件可以變得更簡單:擺脫多余的比較, ngIf已經可以在布爾值上使用:
<div *ngIf="flag" class="loader">Loading...</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.