Increase performance on Angular2 inputfield

妖精的绣舞 提交于 2019-12-19 04:21:52

问题


I have a list of components that contain dates(formatted with toLocaleString()) and other things. On top of them there is a component for creating new components, wich contains a form with some inputfields built with angulars FormBuilder. When I type fast the validation lags and the text I'm typing isn't displayed immediately.

I assume that Angular is rerendering all components, because if I don't display the date in the other components I can type pretty fast without lags.

Is there a way to only rerender the input field I'm typing in, since all other components cannot change or is toLocaleString() the problem?


回答1:


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

Yes, for the components that will not change, set the change detection strategy for those components to OnPush. An OnPush component will then only be checked for changes if

  • any of its input properties changes
  • it fires an event (e.g., a button click)
  • an observable (which is an input property or a local-to-the-component property) fires an event, and | async is used in the template with the observable (see plunker in the comments below this answer)
import {Component, Input, ChangeDetectionStrategy} from 'angular2/core';

@Component({
  ...
  changeDetection: ChangeDetectionStrategy.OnPush
})

Also consider listening for changes to your input by subscribing to the valueChanges Observable Angular makes available on your form element if you use ngFormControl. You can then use debounce() to only process changes every second or whatever time frame is appropriate:

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

See https://stackoverflow.com/a/36849347/215945 for a working plunker.




回答2:


That's a known issue https://github.com/angular/angular/issues/6311

See also

  • https://github.com/angular/angular/issues/5808
  • https://github.com/angular/angular/issues/7822
  • https://github.com/angular/angular/issues/7971

There is also a pull request with a proposed fix, but seems not to be included in the latest beta release.



来源:https://stackoverflow.com/questions/36696308/increase-performance-on-angular2-inputfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!