【问题标题】:*ngIf on component class variable in angular2*ngIf 在 angular2 中的组件类变量上
【发布时间】:2018-06-10 06:09:27
【问题描述】:

我想在标志变量为真时显示加载器,在标志为假时隐藏它(双向数据绑定),但我不知道如何将 *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>

我只想在调用服务时显示加载器 div,并在调用完成后隐藏它。

【问题讨论】:

  • 你有什么问题?
  • 我只想在调用服务时显示加载器,并在调用完成后隐藏它。
  • 你的loader类风格中是否有类似display:none;的东西?如果是这样,请删除该行。

标签: angular angular-components


【解决方案1】:

在响应返回时将您的标志设置为 false。否则,您将立即将其设置为 false:

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

另外,您不需要明确检查true

*ngIf="flag"

如果你愿意,你可以在声明标志时初始化它,而不是在构造函数中进行:

public flag: boolean = true;

【讨论】:

    【解决方案2】:

    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;
        });
    }
    

    PLNKR

    【讨论】:

    • "将this.flag = false; 移动到subscribe 块的success。"我听不懂,你能解释一下吗?
    • 抱歉打错了
    • 让我为你创建一个示例
    • 这对我来说将是莫大的恩惠
    • @UsfNoor : 我创建了一个 plnkr plnkr.co/edit/d5TDgMMj6Vwujbn8hN3N?p=preview
    【解决方案3】:

    您的getData 需要做一些工作:

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

    您的组件可以变得更加简单:去掉额外的比较,ngIf 已经可以处理布尔值了:

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

    【讨论】:

    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 2017-02-27
    • 2017-09-25
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多