Angular FormControl vs FormControlName




Asked on October 16, 2023
What is difference between Angular FormControl and FormControlName and how to use them?



Replied on October 16, 2023
FormControl

FormControl tracks value and validation status of an individual form control such as text, radio button, check box, select box etc.

Find a form control instance to bind a text.

username = new FormControl();

Bind it to text.

<input [formControl]="username"> 

The change in above text can be tracked by using ‘value’ and ‘status’ property of FormControl.

 console.log(username.value);
 console.log(username.status);

status’ gives validation status as valid and invalid.

FormControlName

FormControlName syncs a FormControl in an existing FormGroup to a form control element by name.

Suppose we have a FormGroup with a  FormControl.

userForm = new FormGroup({
   username: new FormControl('',   Validators.maxLength(10))
});

In HTML code, the FormControlName will be used to integrate ‘username’ FormControl with ‘userForm’ FormGroup.

The HTML code will be as given below.

<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
    <input formControlName="username">
</form>

Fetch value and status of FormControl as below.

console.log(userForm.get('username').value);
console.log(userForm.get('username').status);

References: 

https://angular.io/api/forms/FormControl
https://angular.io/api/forms/FormControlName




Write Answer









©2024 concretepage.com | Privacy Policy | Contact Us