简体   繁体   English

* ngIf在angular2中的组件类变量上

[英]*ngIf on component class variable in angular2

I want to show loader when the flag variable is true and hide it when flag is false (two way data binding), but I dont know how to use *ngIf with component variable 我想在标志变量为true时显示加载程序,并在标志为false时将其隐藏(双向数据绑定),但是我不知道如何将* ngIf与组件变量一起使用

app.component.ts 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 default.component.html

    <div *ngIf="flag == true" class="loader">Loading...</div>
    <div class="content">
        <!--my html-->
    </div>

I want to show loader div only when service is call and hide it after call compeleted. 我只想在调用服务时显示loader div,并在调用完成后隐藏它。

Set your flag to false when the response returns. 响应返回时,将标志设置为false。 Otherwise, you are setting it to false immediately: 否则,将立即将其设置为false:

getData() {
    this.flag = true;
    this._service.loadData().subscribe( response => { 
        this.userList = response;
        this.flag = false;
    });
}

Also, you don't need to check for true explicitly: 另外,您不需要显式检查true

*ngIf="flag"

And if you like, you can initialize your flag when you declare it, instead of doing it in the constructor: 并且,如果愿意,可以在声明标志时对其进行初始化,而不用在构造函数中进行操作:

public flag: boolean = true;

Move the this.flag = false; 移动this.flag = false; into the subscribe block's . 进入subscribe块的。 Because of the javascript's async feature, your flag gets set to False before the backend call. 由于javascript具有异步功能,因此在后端调用之前,您的flag将设置为False。

And a simple ngIf condition would be better. 并且简单的ngIf条件会更好。

<div *ngIf="flag" class="loader">Loading...</div>

getData() {
    this.flag = true;
    this._service.loadData().subscribe( response => { 
        this.userList = response;
        this.flag = false;
    });
}

PLNKR PLNKR

Your getData needs a bit of work: 您的getData需要一些工作:

getData() {
    this.flag = true;
    this._service.loadData().subscribe((response) => {
            this.userList = response;
            this.flag = false;
        });
}

And your component can get even simpler: get rid of the extra comparison, ngIf already works on booleans: 而且您的组件可以变得更简单:摆脱多余的比较, ngIf已经可以在布尔值上使用:

<div *ngIf="flag" class="loader">Loading...</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM