1

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.

DBoi
  • 627
  • 2
  • 17
  • 35

1 Answers1

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>
swaroop pallapothu
  • 588
  • 1
  • 6
  • 15
  • This isn't working for me! Should I be importing anything in the component? – DBoi Oct 12 '17 at 10:40
  • Only angular core need to import on component. Did you declared selectedNav in the component? – swaroop pallapothu Oct 12 '17 at 10:43
  • 1
    Got it working now...There was a console issue preventing it from working - "ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions." Thanks for your help – DBoi Oct 12 '17 at 10:47
  • @Dboi Thanks for this comment!! Even I am using form controls. – Dhanashree Jun 08 '18 at 09:33