我的角度应用程序是由一个div包围的标题,主要和页脚结构。 根据标题的高度(响应),我必须在周围的div上设置一个填充顶部。
为此,我将一个名为height的输入参数添加到我从我的app.component传递的header.component中。 在窗口:调整大小我将此参数的值设置为元素offsetHeight并发出此更改,以便app.component识别它。 我还设置了高度ngOnInit以给它一个初始高度。
除了我在控制台中遇到的错误之外,它的效果很好:
AppComponent.html:2 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '160'.
at viewDebugError (core.js:9514)
at expressionChangedAfterItHasBeenCheckedError (core.js:9492)
at checkBindingNoChanges (core.js:9661)
at checkNoChangesNodeInline (core.js:13672)
at checkNoChangesNode (core.js:13646)
at debugCheckNoChangesNode (core.js:14454)
at debugCheckDirectivesFn (core.js:14356)
at Object.View_AppComponent_0._co [as updateDirectives] (AppComponent.html:2)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14338)
at checkNoChangesView (core.js:13486)
有人可以帮我解决这个错误吗?
app.component.html
<div id="stage" [style.padding-top.px]="this.headerHeight">
<app-header [(height)]="this.headerHeight"></app-header>
...
</div>
header.component.ts
import { Component, ElementRef, Input, Output, EventEmitter, OnInit, HostListener } from '@angular/core';
import { OverlayComponent } from './../overlay/overlay.component';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
@Input() height: number;
@Output() heightChange: EventEmitter<number> = new EventEmitter<number>();
constructor(private el: ElementRef) { }
ngOnInit(): void {
this.changeHeight()
}
@HostListener('window:resize')
changeHeight(): void {
this.height = this.el.nativeElement.offsetHeight;
this.heightChange.emit(this.height);
}
}
答案 0 :(得分:1)
当调用ngOnInit()
时模型发生变化时,Angular不喜欢
在更改之后显式调用更改检测以消除错误
export class HeaderComponent implements OnInit {
@Input() height: number;
@Output() heightChange: EventEmitter<number> = new EventEmitter<number>();
constructor(private cdRef:ChangeDetectorRef, private el: ElementRef) { }
ngOnInit(): void {
this.changeHeight();
this.cdRef.detectChanges(); // <<<=== added
}
@HostListener('window:resize')
changeHeight(): void {
this.height = this.el.nativeElement.offsetHeight;
this.heightChange.emit(this.height);
}
}