How to place condition while, looping form array in html

48 Views Asked by At

I have a formarray in the form, Need to hide and show based on dropdown value - is_dependent_exist

I have tried like below:

var all_user_custom_fields = [
  {
    'field_name_slug': 'radio_button_with_group_custom_field8',
    'is_dependent_exist': 0
  },
  {
    'field_name_slug': 'radio_button_with_default_value',
    'is_dependent_exist': 1
  },
  {
    'field_name_slug': 'radio_button_with_mandatory',
    'is_dependent_exist': 1
  },
  {
    'field_name_slug': 'check_box_with_mandatory',
    'is_dependent_exist': 0
  }
];
<div  *ngFor="let CustomUser of custom_field_dataArray.controls; index as c;" [formGroupName]="c" class="col-12 md:col-6 lg:col-4  
*ngIf="all_user_custom_fields[c]?.is_dependent_exist != 1">
<input formControlName="{{all_user_custom_fields[c]?.field_name_slug}}" type="text" (keyup)="validate($event, c, all_user_custom_fields[c]?.field_name_slug)" pInputText />
</div>

Getting issue like Property 'c' does not exist on type 'UsersComponent'.

I need to display only is_dependent_exist = 0 value fields

2

There are 2 best solutions below

1
Ghaith Arfaoui On

It looks like you are trying to use the index variable c within the *ngIf condition, but Angular is complaining because it doesn't recognize the property 'c' on the component class. Instead, you should use the index variable directly without the 'c' property. Here's how you can modify your code:

<div *ngFor="let CustomUser of custom_field_dataArray.controls; index as c" class="col-12 md:col-6 lg:col-4"
  [formGroupName]="c" *ngIf="all_user_custom_fields[c]?.is_dependent_exist !== 1">

  <!-- Your form fields go here -->

</div>

In this code snippet, I removed the unnecessary 'c' property from the *ngIf condition. Now, it should work as expected. This way, you are checking the is_dependent_exist property of the corresponding item in the all_user_custom_fields array based on the index directly.

2
Scryper On

You can't use 2 directives (*ngFor and *ngIf) on the same element.

This should work :

<div *ngFor="let CustomUser of custom_field_dataArray.controls; index as c;" [formGroupName]="c" class="col-12 md:col-6 lg:col-4">
    <div *ngIf="all_user_custom_fields[c]?.is_dependent_exist != 1">
        <input formControlName="{{all_user_custom_fields[c]?.field_name_slug}}" type="text" (keyup)="validate($event, c, all_user_custom_fields[c]?.field_name_slug)" pInputText />
    </div>
</div>