Angular 2 - Show element based on option value selected

时间:2017-10-12 10:18:40

标签: angular angular2-ngmodel

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.

1 个答案:

答案 0 :(得分:3)

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>