0

I'm fairly new to Angular 2, and I'm currently trying to populate a dropdown based on the selection from a different dropdown from mongoDB.

The Problem: I can load the rooms just fine, but whenever I try to load the items(channel) names, it messes up both dropdowns and just shows the first dropdown as empty and the dropdown 2 doesnt show up at all.

I've tried looking for other threads about this topic but they seem to be for Angular 1 instead of Angular 2. Can someone help me out?

Here's my code: app.component.html

<div class="row">
<div class="col-md-12">
    <label>Choose a room</label>
    <select [(ngModel)]="nodes">
        <option *ngFor="let node of nodes"[ngValue]="node">{{node.name}}</option>
    </select>

    <br/><br/>
    <label>Choose an item</label>
    <div *ngFor="let module of node.modules">
        <select [(ngModel)]="channels">
            <option *ngFor="let channel of module.channels">
              {{channel.name}}
             </option>
        </select>
    </div>
</div>

1 Answer 1

2

You're using the node variable in the second ngFor outside of its scope. This variable only exists inside the element(and its attributes) that the ngFor is acting on.

What you probably want to do is wait for changes to the selected value of the first select, update some variable in your controller, which should then cause the second ngFor to update. This can be done by using ngModelChange:

<div class="row">
<div class="col-md-12">
    <label>Choose a room</label>
    <select [(ngModel)]="nodes" (ngModelChange)="selectedNode=$event.target.value">
        <option *ngFor="let node of nodes"[ngValue]="node">{{node.name}}</option>
    </select>

    <br/><br/>
    <label>Choose an item</label>
    <div *ngFor="let module of selectedNode.modules">
        <select [(ngModel)]="channels">
            <option *ngFor="let channel of module.channels">
              {{channel.name}}
             </option>
        </select>
    </div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.