Search code examples
angularform-control

How to create Form filter in angular application?


I want to make a filter with 2 main type input are text and Date type, i create array

arr = [1,2,3]

it's number of filter's row. But when i for loop and then change label to dateOfBirth, all input row changed.

my template file:

  <form [formGroup]="searchAdvanceForm">
            <div class="filter" *ngFor="let item of filterRow; let i= index;">
              <div>{{i + 1}}</div>
              <ng-select [items]="fieldFilter" bindLabel="label" bindValue="value" placeholder="---Choose---"
                         [closeOnSelect]="true" [clearable]="true" formControlName="field{{i}}">
              </ng-select>

              <input *ngIf="searchAdvanceForm.controls.field0.value !== 'dateOfBirth'" class="textFilter" type="text"
                     formControlName="valueSearch{{i}}">

              <nz-date-picker *ngIf="searchAdvanceForm.controls.field0.value === 'dateOfBirth'"
                              [nzFormat]="dateFormat" formControlName="valueSearchDate{{i}}"></nz-date-picker>

              <ng-select [items]="operatorFilter" bindLabel="label" bindValue="value" placeholder="---Choose---"
                         [closeOnSelect]="true" formControlName="operatorSearch{{i}}"></ng-select>
            </div>
  </form>

and here is my UI when normal normal

and when i choose Date of Birth field, the form will like this bug

I expect when i choose Date of birth just this row change type input


Solution

  • You're only referencing controls.field0 but you want to reference the control on the same row.

    <input *ngIf="searchAdvanceForm.get('field' + i).value !== 'dateOfBirth'" ... />
    
    <nz-date-picker
      *ngIf="searchAdvanceForm.get('field' + i).value === 'dateOfBirth'"
      ...
    ></nz-date-picker>