ngModel
and formControlName
cannot be used at the same time on the same form control;
both are used to handle the value of the form control in Angular, but their underlying implementation is different.
ngModel
It is a two-way data binding instruction provided by Angular, which can two-way bind the value of the form control to the properties in the component class. When you ngModel
bind a form control using , it automatically creates and FormControl
binds to the control , and also updates the property values in the template and component class .
formControlName
Is a directive in Angular that is used to associate form controls in templates with corresponding controls in responsive forms . It specifies the name of the form control to be bound via the supplied string parameter and associates it with the corresponding control in the parent FormGroup
or .FormArray
Since ngModel
and formControlName
are both used to process the value of a form control, applying them both to the same form control can cause conflicts .
Typically, it is recommended to use reactive forms and formControlName
bind them via the template instead of using ngModel
. If you need to two-way bind the value of a form control, you can use to valueChanges
subscribe to changes in the form control value and manually update the property value in the component class.
<form [formGroup]="myForm">
<input type="text" formControlName="myControl">
</form>
<form [formGroup]="paramForm">
<input type="text" formControlName="myControl2">
</form>
import {
Component, OnInit } from '@angular/core';
import {
FormGroup, FormControl, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-component',
template: `...`
})
export class MyComponent implements OnInit {
myForm: FormGroup;
paramForm: FormGroup;
constructor(
private formbuilder: FormBuilder,
) {
this.paramForm = this.formbuilder.group({
});
}
ngOnInit() {
// 写法1:
this.myForm = new FormGroup({
myControl: new FormControl()
});
// 写法2:
this.paramForm.addControl(
'myControl2',
this.formbuilder.control('initialValue', [...]),
); // ... 表示校验内容
}
}
The above example creates a responsive form and binds it to the form controls in the template. The name of the form control to be bound is specified by formControlName
, and the corresponding object is created in the component class FormControl
. This way, the form control's values will automatically stay in sync with the properties in the component class.