在Angular响应式表单中,可以通过使用patchValue
方法来在(change)
事件回调中保留旧值。以下是一个示例代码:
在组件类中定义一个表单控件,并初始化其值:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-example',
template: `
`,
})
export class ExampleComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
myControl: ['Initial Value']
});
}
preserveOldValue(event: any) {
const oldValue = this.myForm.get('myControl').value;
this.myForm.patchValue({
myControl: oldValue
});
}
}
在上述代码中,我们通过patchValue
方法将表单控件的值重新设置为旧值,保留了旧值。在每次(change)
事件触发时,都会调用preserveOldValue
方法。
请注意,preserveOldValue
方法中的event
参数可以根据需要进行使用,例如获取最新的值或其他相关信息。