[Fixed] Angular Forms with string values and *ngIf


I’m trying to not display forms in a list if they are empty. The form’s values are string. I tried to use *ngIf but, it didn’t work and I can still see empty places in the list. How can I solve this? (In the image, ISRawMaterialInspection and ISRawMaterialRiskState are the ones that are empty.)

Here is the HTML:

<input matInput class="mt-20" formControlName="IsOxidizable" *ngIf="form.get('IsOxidizable').value"/>

    <input matInput class="mt-20" formControlName="ISRawMaterialInspection" *ngIf="!!form.get('ISRawMaterialInspection').value"/>
    <input matInput class="mt-20" formControlName="ISRawMaterialRiskState" *ngIf="form.get('ISRawMaterialRiskState').value"/>

Here is the TS:

        IsOxidizable: new FormControl({
            value: this.data.IsOxidizable,
            disabled: true,
        ISRawMaterialRiskState: new FormControl({
            value: this.data.ISRawMaterialRiskState,
            disabled: true,
        ISRawMaterialInspection: new FormControl({
            value: this.data.ISRawMaterialInspection,
            disabled: true

enter image description here


After some comment Input from Eliseo my previous answer needed some edit.

As Eliseo stated

if(a) condition in typescript is false if a is equal to undefined,
null, "",0 or false

    <input matInput class="mt-20" formControlName="IsOxidizable" *ngIf="form.get('IsOxidizable').value && form.get('IsOxidizable').value !== ''"/>

    <input matInput class="mt-20" formControlName="ISRawMaterialInspection" *ngIf="form.get('ISRawMaterialInspection').value form.get('IsOxidizable').value !== ''"/>
    <input matInput class="mt-20" formControlName="ISRawMaterialRiskState" *ngIf="form.get('ISRawMaterialRiskState').value form.get('IsOxidizable').value !== ''"/>

But considering that OP has accepted the answer and probably solved the problem, there is a catch here.

var a = new String('');

if (a) -> will evaluate to true

So maybe OP didn’t use primitive string, but String objects.

if(a) condition in typescript is false if a is equal to undefined,
null, "",0 or false only for primitive data types.

if (new Boolean(false)) -> evaluates to true
if (new String('')) -> evaluates to true
if (new Number(0)) -> evaluates to true

In the end thanks Eliseo for clarification which helped me get better.

Leave a Reply

(*) Required, Your email will not be published