ngOnInit()에 회 전자를 표시하고 ngAfterViewInit()에서 숨기려고합니다. 에서는 setTimeout()없이라이프 사이클 후크 방법에서 Angular2 변경 감지
- 는, 아무것도에서는 setTimeout(), 회 전자 쇼 숨기기 (깜박)와
- 일이 없지만, ngAfterViewInit() 후
http://plnkr.co/edit/M1g7DT1Eks2gtuSXi1B1?p=preview
: 하지만이 작동하지 않습니다이 예제에서 스피너 구성 요소 (spinner.ts)는 배경색을 변경하는 div 태그입니다. (mycomponent.ts) '내 구성 요소에 대한 링크'에 카릭에
import {Component, Input} from '@angular/core'
@Component({
selector: 'my-spinner',
template: `
<div [style.background-color]="status ? 'red' : 'yellow'" >
spinner is {{status}}
</div>
`,
})
export class MySpinner {
@Input() status: boolean;
status:boolean;
constructor() {
this.status = false;
}
getColor() {
if (status) {
return "red";
} else {
return "yellow";
}
}
ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
for (let propName in changes) {
let chng = changes[propName];
let cur = JSON.stringify(chng.currentValue);
let prev = JSON.stringify(chng.previousValue);
console.trace(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
}
}
}
, 나는 배경색 스피너가 ngOnInit()와 ngAfterViewInit() 사이에 빨간색합니다.
import {Component, Input, ApplicationRef} from '@angular/core';
import {AppService} from './appservice';
@Component({
selector: 'my-component',
template: `
<div>
This is my component!
</div>
`,
})
export class MyComponent {
constructor(private appSvc: AppService) {
}
ngOnInit(): void {
this.appSvc.setVisible(true);
console.log('MyComponent - ngOnInit');
}
ngAfterViewInit() {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > 10000){
break;
}
}
//setTimeout(() => { this.appSvc.setVisible(false)});
this.appSvc.setVisible(false);
console.log('MyComponent - ngAfterViewInit');
}
}
해결책은 무엇입니까?
UPDATE
나는 관찰 사용하는 샘플 http://plnkr.co/edit/M1g7DT1Eks2gtuSXi1B1?p=preview를 업데이트합니다.
나는 ngOnInit()하지만 ngOnChanges() 회 전자 부품의 ngAfterViewInit (후라고합니다)
로그 콘솔이에 표시 할 스피너를 설정합니다
VM437 AppService - setVisible - true
VM439 mycomponent.ts!transpiled:33 MyComponent - ngOnInit
VM439 mycomponent.ts!transpiled:37 MyComponent - ngAfterViewInit -begin
VM439 mycomponent.ts!transpiled:47 MyComponent - ngAfterViewInit -end
**VM440 spinner.ts!transpiled:38 status: currentValue = true, previousValue = fals**
VM437 appservice.ts!transpiled:27 AppService - setVisible - false
VM439 mycomponent.ts!transpiled:45 Observable Complete
**VM440 spinner.ts!transpiled:38 status: currentValue = false, previousValue = true**
그래서이 보인다 라이프 사이클 훅 메소드에서 즉시 감지를 변경하지 않습니까? 옳고 그름?
이 두 라이프 사이클 후크에서 요소를 보이고 숨기는 목적이 무엇인지 설명해주십시오. – jmachnik
이것은 가능한 한 빨리 (ngOnInit()에서) 스피너를 보여 주지만, ngAfterViewInit() 이후에만 표시됩니다. 내 질문이 나는 내 질문을 업데이트하고 관찰 가능을 사용하도록 예제를 변경합니다 – dombr