Angular - my ngIf hides an input-label only once

Viewed 1437

*ngIf="currentIdea.oetSupportNeeded" I have a dropdown list with 2 values - yes and no, and another input label where you can write freely. I want to show the input-label only when user chose "yes" in the dropdown list and to hide it when "no" is chosen.

My problem is that the following code works only once - when page loads and "no" is chosen, the input label is hidden, but when you choose "yes" and then "no" again, the label shows up and doesn't disappear anymore. I want it to toggle on/off depending on the user's choice

I tried using ngShow, ngHide, [disabled], etc. Nothing helped

<div class="select-wrapper" [ngClass]="{'select-wrapper-blocked': isNotAdmin()}">
            <select class="input-control" [(ngModel)]="booleanVariable">
                <option value="false">No</option>
                <option value="true">Yes</option>
            </select>
        </div>
    </div>

    <div class="col form-input" [ngClass]="{'form-input-blocked': isNotAdmin()}">
        <p class="input-label">
            Some text
        </p>
        <input *ngIf="booleanVariable" class="input-control" [(ngModel)]="stringVariable" />
    </div>
4 Answers

You are using true and false as strings. You can change the test into your ngIf.

Like

<select [(ngModel)]="foo">
  <option [ngValue]="true">true</option>
  <option [ngValue]="false">false</option>
</select>
<input *ngIf="foo == true"/>

And to define a default value, you can set the value of foo into the class like

public foo = true;

According to the code you shared, the value of your select menu is bound to the booleanVariable property of your component. Your *ngIf queries another property, so the condition is wrong. You should be checking the booleanVariable in the condition.

Something similar happened to me few hours ago. The problem was that

<option value="false">No</option> <option value="true">Yes</option> was wrong. I solved it with

<option [value]="false">No</option> <option [value]="true">Yes</option>

That's because otherwise Angular does not "analyze" the value of the option but recognizes it as a string.

Related