gpt4 book ai didi

performance - 提高 Angular2 输入字段的性能

转载 作者:行者123 更新时间:2023-12-03 06:14:33 24 4
gpt4 key购买 nike

我有一个包含日期(使用 toLocaleString() 格式化)和其他内容的组件列表。在它们之上有一个用于创建新组件的组件,其中包含一个表单,其中包含一些使用 Angulars FormBuilder 构建的输入字段。当我快速键入时,验证会出现滞后,并且我正在键入的文本不会立即显示。

我假设 Angular 正在重新渲染所有组件,因为如果我不在其他组件中显示日期,我可以快速输入而不会出现延迟。

有没有办法只重新渲染我正在输入的输入字段,因为所有其他组件都无法更改,或者是 toLocaleString() 存在问题?

最佳答案

Is there a way to only rerender the input field I'm typing in, since all other components cannot change

是的,对于不会发生变化的组件,将这些组件的变化检测策略设置为OnPush。仅当满足以下条件时才会检查 OnPush 组件是否发生更改:

  • 其任何输入属性发生变化
  • 它触发一个事件(例如,单击按钮)
  • 一个可观察对象(它是一个输入属性或组件的本地属性)触发一个事件,并且 | async 在模板中与 observable 一起使用(请参阅本答案下方评论中的 plunker)
import {Component, Input, ChangeDetectionStrategy} from 'angular2/core';

@Component({
...
changeDetection: ChangeDetectionStrategy.OnPush
})
<小时/>

如果您使用 ngFormControl,还可以考虑通过订阅 Observable Angular 在表单元素上提供的 valueChanges 来监听输入的更改。然后,您可以使用 debounce() 每秒或任何合适的时间范围仅处理更改:

<input type=text [ngFormControl]="input1Control">
constructor() { 
this.input1Control = new Control();
}
ngOnInit() {
this.input1Control.valueChanges
.debounceTime(1000)
.subscribe(newValue => console.log(newValue))
}

参见https://stackoverflow.com/a/36849347/215945对于一个正在工作的笨蛋来说。

关于performance - 提高 Angular2 输入字段的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696308/

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