使用Angular中的Reactive Forms来解决这个问题。可以使用FormControl来捕获和管理表单中的值,而不是通过[(ngModel)]来获取输入值。下面是一个示例代码:
HTML文件:
TypeScript文件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
constructor() { }
ngOnInit(): void {
this.myForm = new FormGroup({
inputValue: new FormControl('')
});
}
onInputChange(): void {
const inputValue = 'new value';
this.myForm.get('inputValue').setValue(inputValue);
}
}
在上面的代码中,我们使用了FormControl来捕获和管理输入值。在组件的ngOnInit函数中,我们创建了一个名为myForm的FormGroup并将其分配给组件的属性。在模板中,我们指定FormGroup中的表单控件名称作为formControlName指令的属性值。此外,还可以使用setValue函数来更改输入框的值,在此示例中,我们通过onInputChange函数将输入框的值更改为'new value”。
这种方法比使用[(ngModel)]来获取和更改输入值更加灵活和可靠。