在Angular中,可以通过使用双向数据绑定将两个表单控件绑定到同一个模型。以下是一个使用Angular的解决方法的示例代码:
在组件类中声明一个模型变量和两个表单控件的变量:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
Full Name: {{ fullName }}
`
})
export class FormComponent {
firstNameControl = new FormControl();
lastNameControl = new FormControl();
fullName: string;
constructor() {
this.firstNameControl.valueChanges.subscribe(value => {
this.fullName = value + ' ' + (this.lastNameControl.value || '');
});
this.lastNameControl.valueChanges.subscribe(value => {
this.fullName = (this.firstNameControl.value || '') + ' ' + value;
});
}
}
在上面的代码中,我们创建了两个表单控件 firstNameControl
和 lastNameControl
,并将它们分别绑定到了两个输入框。然后,我们订阅了每个表单控件的 valueChanges
事件,并在事件处理程序中更新了 fullName
变量。
请注意,在这个示例中,我们使用了 valueChanges
事件来监听每个表单控件的值变化。每当一个输入框的值发生变化时,我们将更新 fullName
变量,该变量会在模板中显示完整的姓名。
确保在组件类中导入了 FormControl
从 @angular/forms
包,以便能够使用 FormControl
类。
最后,我们将 FormComponent
添加到父组件的模板中,以便在页面上显示表单。