I am creating a form group with a checkbox in Angular 13. Here, the field of receiver code is disabled by default. How can I enable this input field when the checkbox is checked and disable when it's not?
in my .ts I have:
export class IntPayComponent implements OnInit {
paymentDetails!: FormGroup;
disabled = true;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.paymentDetails = this._formBuilder.group({
receiver_code: new FormControl({value:"", disabled: true})
});
}
and in my html template I have:
<mat-stepper [linear]="isLinear" #stepper>
<mat-step [stepControl]="paymentDetails">
<form [formGroup]="paymentDetails">
<div class="add-directory">
<mat-checkbox>Add to Directory</mat-checkbox>
</div>
<div class="reference-field">
<mat-form-field appearance="fill" floatLabel="always">
<mat-label>Receiver Code</mat-label>
<input matInput formControlName="receiver_code"/>
</mat-form-field>
</div>
</form>
</mat-step>
</mat-stepper>
You need to make the checkbox into a FormControl, say
addDirectory:Then, after the
FormGroupinitialisation, you listen to itsvalueChangesObservable and modifyreceiver_code's disabled state accordingly:You could make things a bit cleaner by setting the
FormControlsup as independent from theFormGroup, meaning you don't have to keep callinggetto get access to them.Also, FYI, you don't use the HTML
disabledattribute when working with reactive forms. No doubt Angular has displayed a warning about this in the console.