how to set form control value in angular
How to Set Form Control Value in Angular?
If you are working with forms in Angular, you may need to set the value of a form control programmatically. There are different ways to do it, but here are some examples:
1. Using setValue() method
You can use the setValue()
method of the FormControl
class to set the value of a form control. Here is an example:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<form>
<input type="text" [formControl]="nameControl">
</form>
`
})
export class AppComponent {
nameControl = new FormControl('');
ngOnInit() {
this.nameControl.setValue('John Doe');
}
}
In this example, we create a form control called nameControl
and bind it to an input element using the [formControl]
directive. Then, in the ngOnInit()
method of the component, we set the value of the form control to 'John Doe'
using the setValue()
method.
2. Using patchValue() method
You can also use the patchValue()
method of the FormControl
class to set the value of a form control. Here is an example:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<form>
<input type="text" [formControl]="nameControl">
</form>
`
})
export class AppComponent {
nameControl = new FormControl('');
ngOnInit() {
this.nameControl.patchValue('John Doe');
}
}
In this example, we create a form control called nameControl
and bind it to an input element using the [formControl]
directive. Then, in the ngOnInit()
method of the component, we set the value of the form control to 'John Doe'
using the patchValue()
method.
3. Using setValue() method with an object
You can also use the setValue()
method with an object to set the values of multiple form controls at once. Here is an example:
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<form [formGroup]="form">
<input type="text" formControlName="firstName">
<input type="text" formControlName="lastName">
</form>
`
})
export class AppComponent {
form = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl('')
});
ngOnInit() {
this.form.setValue({
firstName: 'John',
lastName: 'Doe'
});
}
}
In this example, we create a form group called form
with two form controls: firstName
and lastName
. Then, in the ngOnInit()
method of the component, we set the values of both form controls using the setValue()
method with an object.
Conclusion
These are some ways to set the value of a form control in Angular. Depending on your use case, you may choose one of these methods or another one. Just remember that you need to import the FormControl
and/or FormGroup
classes from the @angular/forms
module to use them.