gpt4 book ai didi

javascript - Angular :ExpressionChangedAfterItHasBeenCheckedError

转载 作者:行者123 更新时间:2023-11-27 23:08:57 26 4
gpt4 key购买 nike

我的 Angular 应用程序的结构是页眉、主体和页脚,周围是一个 div。根据标题的高度(它是响应式的),我必须在周围的 div 上设置 padding-top。

为此,我向从 app.component 传递的 header.component 添加了一个名为 height 的输入参数。在 window:resize 上,我将此参数的值设置为元素 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);
}
}

最佳答案

Angular 不喜欢调用 ngOnInit() 时模型发生变化。
在更改后显式调用更改检测以消除错误

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

关于javascript - Angular :ExpressionChangedAfterItHasBeenCheckedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47437135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com