gpt4 book ai didi

javascript - NgOnChanges 在用户键入时覆盖表单控件值

转载 作者:行者123 更新时间:2023-11-30 19:29:17 25 4
gpt4 key购买 nike

我有自动完成表单控件:

@Component({
selector: 'app-autocomplete',
templateUrl: './app-autocomplete.view.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AutoCompleteFilterComponent implements OnInit, OnDestroy, OnChanges {
@Input() value: any;
@Output() onChanged = new EventEmitter();
autoCompleteControl: FormControl = new FormControl();
private autoCompleteControlSubscription: Subscription;
constructor() { }

ngOnInit(): void {
this.autoCompleteControl.setValue(this.value, { emitEvent: false });
this.autoCompleteControlSubscription = this.autoCompleteControl.valueChanges
.pipe(
skipUndefined(),
filter(value => value.length >= 3),
distinctUntilChanged(),
debounceTime(350),
map(value => {
this.onChanged.emit(value.trim());
})
).subscribe();
}

ngOnChanges(changes: SimpleChanges): void {
if (!changes.value.firstChange) {
this.autoCompleteControl.setValue(changes.value.currentValue);
}
}

ngOnDestroy(): void {
if (this.autoCompleteControlSubscription) {
this.autoCompleteControlSubscription.unsubscribe();
}
}

我从 store 获取初始值并将其作为 @Input 变量传递:

this.value$ = this._store$.select(s=>s.value);
<app-autocomplete [value]="value$ | async"></app-autocomplete>

我遇到的问题是:

  1. 组件加载,我从 store 传递初始 value
  2. 用户在输入文本字段中输入内容。
  3. 用户停止打字 350 毫秒(去抖动 时间)。
  4. 向父级发出值,并使用Action + Reducer 将值保存在存储中。
  5. this.value$ Observable 响应 store 变化并触发 ngOnChange 方法。
  6. 用户继续输入。
  7. store 中的值会覆盖用户已经输入的内容。

例如,用户键入“stri”,然后稍作停顿,然后键入“string”,但是“store”值覆盖了他的“string”值,他得到了我之前放入“store”的“stri”值。有没有人遇到过这个?我们想出的唯一解决方案是检查焦点并且不设置新值。

最佳答案

您正在订阅 ngOnInit 中的更改:

this.autoCompleteControlSubscription = this.autoCompleteControl.valueChanges

还有 ngOnChanges。

this.autoCompleteControl.setValue(changes.value.currentValue);

我将试一试您正在尝试做的事情:

  1. 在初始化时,您可能需要修补值并然后设置订阅,这样它们就不会相互干扰。

  2. 如果您想在不触发表单的 valueChanges 的情况下修补值,那么在没有事件的情况下进行修补:

    this.form.controls[control].patchValue(value, { emitEvent: false });

看看我是如何在 StackBlitz 上使用我自己的 ControlValueAccessor 控件组件执行此操作的.我使用 writeValue

设置初始控制值(如果有的话)

关于javascript - NgOnChanges 在用户键入时覆盖表单控件值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56602850/

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