ngModel and formControlName handle form controls

ngModeland formControlNamecannot 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.

ngModelIt 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 ngModelbind a form control using , it automatically creates and FormControlbinds to the control , and also updates the property values ​​in the template and component class .

formControlNameIs 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 FormGroupor .FormArray

Since ngModeland formControlNameare 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 formControlNamebind 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 valueChangessubscribe 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.

Guess you like

Origin blog.csdn.net/weixin_45678402/article/details/132320280