quma
quma

Reputation: 5733

Angular 5 - conditional required textarea

If checkbox is clicked than textarea appears and is required [required]="otherVendorsChecked == true ? true : false" If I select checkbox and than deselect it a textarea input is still required. Does anyone know what I am doing wrong?

<div>
    <mat-checkbox [ngModelOptions]="{standalone: true}" [(ngModel)]="otherVendorsChecked">Other option:</mat-checkbox>
</div>
<mat-form-field *ngIf="otherVendorsChecked == true">
    <textarea matInput formControlName="otherVendors" [required]="otherVendorsChecked == true ? true : false"></textarea>
</mat-form-field>

[EDIT]

If I remove *ngIf="otherVendorsChecked == true" than it works fine. I guess that mat-form-field is only removed with ngIf condition and therefore has no more influence to the required property.

This is my form in ngOnInit:

this.form = new FormGroup({
  otherVendors: new FormControl('', [Validators.minLength(2)]),
  ...
});
this.fillForm();

and in my fillForm I have this code:

this.form.controls['otherVendors'].setValue(this.lastFacilityDetailOfCalendarEvent.otherVendors);
    if(this.lastFacilityDetailOfCalendarEvent.otherVendors != null && this.lastFacilityDetailOfCalendarEvent.otherVendors.length > 0) {
      this.otherVendorsChecked = true;
    }

Upvotes: 2

Views: 2721

Answers (1)

Amaresh C.
Amaresh C.

Reputation: 599

[Edited]

Finally, After little bit of experimentation, I can see that it's all because of <mat-form-field *ngIf="otherVendorsChecked == true">.

Every time you change otherVendorsChecked value, FormControl will be toggled between required and not required. When otherVendorsChecked is true, your FormControl will be changed to required and but when otherVendorsChecked changed to false, Even before updating your FormControl to not required *ngIf will remove the textarea element from the DOM before triggering the change event of FormControl, so now FormControl has no idea to make it not required.

For a quick fix, Instead of using *ngIf You can just hide that section/element from view, maybe using display: none; or something like that.

Hope this helps.

Upvotes: 2

Related Questions