Search code examples
angularangular7formarray

On Select change show div content according to value FormArray Angular 7


I am developing a form in Angular 7, I am using Reactive Form which has FormArray in it.

There are <select></select> control in each FormArray

This is Form Structure

this.form = this.formBuilder.group({
      'listid': ['', [Validators.required]],
      'segmentName': ['', [Validators.required]],
      'description': ['', [Validators.required]],
      listFieldArray: this.formBuilder.array([])
    });

And this is FormArray Structure

addListFieldsFormGroup(name: string, value: string): FormGroup {
    return this.formBuilder.group({
      'condition': ['', [Validators.required]],
      'name': [name],
      'value': [value, [Validators.required]],
      'type': ['1', [Validators.required]],
      'operator': ['', [Validators.required]],
      'operand': ['', [Validators.required]]
    });
  }

condition in FormArray is a Select Control, on chage of this select, I want to show Div according to value

<div class="clr-row">
          <clr-select-container>
            <select clrSelect formControlName="sentCondition">
              <option value="">Select </option>
              <option value="custom">Custom</option>
              <option value="between">Between</option>
              <option value="lessThenEqual">Less then or Equal</option>
              <option value="moreThen">More then</option>
            </select>
          </clr-select-container>
        </div>
        <div class="clr-row" *ngIf="sentCondition==='custom'">
          <div class="clr-col-4 ">
            <input clrInput placeholder="From Day" type="date" formControlName="customDayFrom" />
          </div>
          <div class="clr-col-4 ">
            <input clrInput placeholder="To Day" type="date" formControlName="customDayTo" />
          </div>
        </div>
        <div class="clr-row" *ngIf="sentCondition==='between'">
          <div class="clr-col-4 ">
            <input clrInput placeholder="From Day" formControlName="customDayFrom" />
          </div>
          <div class="clr-col-4 ">
            <input clrInput placeholder="To Day" formControlName="customDayTo" />
          </div>
        </div>
        <div class="clr-row" *ngIf="sentCondition==='lessThenEqual' || sentCondition==='moreThen'">
          <div class="clr-col-4 ">
            <input clrInput placeholder="Day" formControlName="customDayFrom" />
          </div>
        </div>

It was working with [(ngModel)] but now it is deprecated in Angular 7 with Reactive Form.


Solution

  • You can use hash on select something like

     <select clrSelect formControlName="sentCondition" #someHashName>
    

    then on div use if condition something like

    <div *ngIf="someHashName?.value == 'yourcondition'">