gpt4 book ai didi

angular - 错误错误: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Angular

转载 作者:行者123 更新时间:2023-12-03 07:56:22 26 4
gpt4 key购买 nike

我正在尝试使组件具有响应性。处理Windows调整大小。值将通过表达式 getRight()给出。

我的HTML:

<div [hidden]="index > 3" [style.right]="getRight()" class="chat-box card">
............
</dv>
在我的component.ts中
import { Component, HostListener } from '@angular/core';

@Component({
selector: 'app-chat-box',
templateUrl: './chat-box.component.html',
styleUrls: ['./chat-box.component.scss']})

export class ChatBoxComponent implements OnInit {

@HostListener('window:resize', ['$event'])
onResize(event) {this.currentWidth = event.target.innerWidth;}

currentWidth: number;

constructor(){}
ngOnInit() {}

getRight() {
if(this.currentWidth <= 700 || window.innerWidth <= 700){
if(this.currentWidth){
return ((this.currentWidth -320)/2).toString() + 'px';
}
return ((window.innerWidth -320)/2).toString() + 'px';
}
if(this.index==1 && window.innerWidth > 700 ){
return '380px';
}
return (380 +330).toString() + 'px';} }
错误信息将是:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'right: 710px'. Current value: 'right: 11px'.

最佳答案

那不是你应该怎么做。该函数将在每个更改检测周期被调用。更好的方法是响应调整大小,然后才进行计算。更高效的方式:

<div [hidden]="index > 3" [style.right.px]="right" class="chat-box card"></div>
export class ChatBoxComponent implements OnInit {
right: number;

@Input()
index?: number;

@HostListener('window:resize')
setRight() {
const width = window.innerWidth;

if (width <= 700) {
this.right = ((width - 320) / 2);
} else if (this.index === 1 && width > 700) {
this.right = 380;
} else {
this.right = 380 + 330;
}
}

ngOnInit(): void {
this.setRight();
}

ngOnChanges(changes: SimpleChanges): void {
if (changes.index) {
this.setRight();
}
}
}
我忽略了您已实现的一些怪异逻辑,但我建议您也更好地了解angular.io上的 Angular 导轨
但是,我建议您使用 OnPush更改检测策略。这将已经大大减少了 ExpressionHasChanged错误的数量,使您的应用程序更具性能,并增加了何时进行更改检测的逻辑。

一种更高级的方法是将 async管道与 rxjs结合使用:
<div [hidden]="(index$ | async) > 3" [style.right.px]="right$ | async" class="chat-box card"></div>
export class ChatBoxComponent {
@Input()
set index(index: number) {
this.index$.next(index || 0);
}

readonly index$ = new BehaviorSubject<number>(0);

readonly right$: Observable<number> = combineLatest([
this.index$,
fromEvent(window, 'resize').pipe(
startWith<Event, void>(void 0)
)
]).pipe(
map(([index]) => this.getRight(index))
);

private getRight(index: number): number {
const width = window.innerWidth;

if (width <= 700) {
return (width - 320) / 2;
}

if (index === 1 && width > 700) {
return 380;
}

return 380 + 330;
}
}
working example

关于angular - 错误错误: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63520896/

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