Angular 2 - Show element based on option value selected

DBoi picture DBoi · Oct 12, 2017 · Viewed 8.6k times · Source

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.

Answer

swaroop pallapothu picture swaroop pallapothu · Oct 12, 2017

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>