Search code examples
javascripthtmlangularangular-formsdynamic-forms

Angular | NgRx Check for null field in an object before putting it in a list of dropdown


I have a html dropdown which is sourcing data from an api, the api returns an array of objects [in the component]. The Dropdown uses a field value which is in most objects, but not all.

So it causes, some fields entries to show blank in the dropdown.

<div class="col-sm-5">
                    <label>DropDown<label class="field-importance" style="padding-left: 14rem">Required</label></label>
                    <select formControlName="Entry" placeholder="Select Entry" required>
                        <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
                        <option *ngFor="let e of entry" [value]="e.val">{{e.val}}</option>
                    </select>
</div>

enter image description here

Thank you soo much


Solution

  • You could do a *ngIf check for val property before using it. Try the following

    <div class="col-sm-5">
      <label>DropDown<label class="field-importance" style="padding-left: 14rem">Required</label></label>
      <select formControlName="Entry" placeholder="Select Entry" required>
        <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
        <ng-container *ngFor="let e of entry">
          <ng-container *ngIf="e.val">
            <option [value]="e.val">{{e.val}}</option>
          </ng-container>
        </ng-container>
      </select>
    </div>