[英]Angular2 change detection in lifecycle hook methods
我想在ngOnInit()中顯示一個微調框,然后在ngAfterViewInit()中將其隱藏。 但這不起作用:
http://plnkr.co/edit/M1g7DT1Eks2gtuSXi1B1?p=preview
在此示例中,微調器組件(spinner.ts)是一個div標簽,用於更改背景顏色。
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}`);
}
}
}
關於“鏈接到我的組件”(mycomponent.ts),我希望背景顏色微調器在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**
因此,似乎在生命周期掛鈎方法中沒有立即進行更改檢測? 對還是錯?
為此,我認為最好將微調框作為非角度組件直接放在<my-app>
標記內。 這樣,您可以獲得在應用程序完全加載之前一直顯示的微調器。
如果嘗試使用角度組件來實現此目的,則直到加載了角度應用程序后,微調器才會顯示,並且當加載了角度應用程序時,此時微調器是無用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.