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.

0

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't working for me! Should I be importing anything in the component?
Only angular core need to import on component. Did you declared selectedNav in the component?
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 Thanks for this comment!! Even I am using form controls.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.