2017-12-29 25 views
2

플래그 변수가 true 일 때 로더를 표시하고 플래그가 거짓 (양방향 데이터 바인딩) 일 때 숨기려고하지만 구성 요소 변수에 * ngIf를 사용하는 방법을 모르겠다.* ngIf에서 angular2의 구성 요소 클래스 변수에

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

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

서비스가 호출 될 때만 로더 div를 표시하고 통화가 compeleted 된 후에 숨기려고합니다.

+0

어떤 문제가 있습니까? – user184994

+0

서비스가 호출 될 때만 로더를 표시하고 호출이 완료된 후에 숨기려고합니다. –

+0

'display : none;'과 같은 것이'loader' 클래스 스타일에 있나요? 그렇다면 해당 행을 제거하십시오. – ConnorsFan

답변

1

귀하의 getData는 약간의 작업이 필요 :

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

을 그리고 구성 요소도 간단하게 얻을 수 있습니다 : 여분의 비교를 제거, ngIf은 이미 부울에서 작동합니다.

+0

저를 위해 작동하지 않습니다 –

+1

@UsfNoor 여기에서 예제를 확인하십시오 : https://stackblitz.com/edit/angular-loader?file=app%2Fapp.component.html – Zlatko

2

응답이 반환되면 플래그를 false로 설정하십시오. 그렇지 않으면, 즉시 false로 설정됩니다

*ngIf="flag" 

을 그리고 만약 당신이 좋아하면, 당신은 당신이 선언 할 때 플래그를 초기화 할 수 있습니다 : 또한

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

, 당신은 명시 적으로 true를 확인 할 필요가 없습니다 그 대신 생성자에서 그 일의 :

public flag: boolean = true; 
+0

나를 위해 작동하지 않습니다 –

2
subscribe 블록의에 this.flag = false; 이동

. 자바 스크립트의 비동기 기능으로 인해 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

+0

"'this.flag = false;'를'subscribe' 블록의'success' 블록으로 옮깁니다." 나는 이것을 얻을 수 없다, 나는 당신을 설명 할 수 있냐? 나는 plnkr을 만든 https://plnkr.co을 : –

+0

미안은이 코드는 나를 위해 작동하지 실수 –

+0

를 입력 한 것, 로더는 나를 위해 –