简体   繁体   中英

Conditional statement not working in Angular ngIf

I am working on sample project in which i am using GET request to fetch the data from API and storing it array. And using that array i am creating radio buttons.

Example

Array

[
{
active: 0
categoryId: 8
categoryName: "ItemCustomerType"
codeName: "All"
description: "Type"
globalCodeId: 5
},
{
active: 0
categoryId: 8
categoryName: "ItemCustomerType"
codeName: "Agent"
description: "Type"
globalCodeId: 21
},
{
active: 0
categoryId: 8
categoryName: "ItemCustomerType"
codeName: "Private"
description: "Type"
globalCodeId: 22
}
]


Now i want to show only those radio buttons whose "codeName" value = Private or"codeName" value = Agent

Code for Radio Button

                    <label class="radioBtn" *ngFor="let customerCodeName of itemSourceData;let i = index">{{customerCodeName.codeName}}
                      <input type="radio" value="{{customerCodeName.codeName}}"
                             (change)="onChangeItemSource(customerCodeName.codeName)" formControlName="itemType">
                      <span class="checkmark"></span>
                    </label>

**here itemSourceData contains the data fetched from API in form of array. But the PROBLEM is it is showing 3 radio buttons for codeName:'All','Agent','Private' but it should show only 2 radio buttons for 'Agent' and 'Private' only **.

Any solution please?

Filter your list for your loop.

let list = itemSourceData.filter(i=>i.codeName==='Private'||i.codeName==='Agent');

Please add an if statement in your input type to only add radio buttons if it is Private or Agent inside for loop.

HTML

<label class="radioBtn" *ngFor="let customerCodeName of itemSourceData; let i = index"
  >{{ customerCodeName.codeName }}
  <input
    *ngIf="
      customerCodeName.codeName === 'Private' || customerCodeName.codeName === 'Agent'
    "
    type="radio"
    value="{{ customerCodeName.codeName }}"
    (change)="onChangeItemSource(customerCodeName.codeName)"
    formControlName="itemType"
  />
  <span class="checkmark"></span>
</label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM