Angular 2 – Show element based on option value selected

Issue

I’m looking for the cleanest way to show an element based on what is selected from a form drop down menu in Angular 2.

I have tried a fair few different techniques but still no luck!

Here is what i currently have:

HTML:

<fieldset class="full-width sm-padding">
    <label>What existing cover do you already have?</label>
    <select id="existingCover" [(ngModel)]="selectedNav">
        <option *ngFor="let dropDown of existingCoverList">
            {{dropDown.option}}
        </option>
    </select>
</fieldset>


<div *ngIf="selectedNav === 'Cover1'">Show this element if option 1 is selected!</div>

TYPESCRIPT:

existingCoverList: any[] = [
    { option: 'Cover1' },
    { option: 'Cover2' },
    { option: 'Cover3' }];

What am I doing wrong?

Thanks for your help on this.

Solution

Follow below code you will get the expected result. This thing i added to your code

HTML:

<fieldset class="full-width sm-padding">
    <label>What existing cover do you already have?</label>
    <select id="existingCover" [(ngModel)]="selectedNav">
        <option [value]="dropDown.option" 
            *ngFor="let dropDown of existingCoverList">
            {{dropDown.option}}
        </option>
    </select>
</fieldset>


<div *ngIf="selectedNav === 'Cover1'">Show this element if option 1 is selected!</div>

Answered By – swaroop pallapothu

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.