In my application developed using Angular 2, on selection of a dropdown the ngModel does update the variable declared in the component but the value does not reflect in the "change" event handler of the dropdown.
Here is the concerning HTML code.
<div class="modal-body">
<form #wallForm="ngForm" (ngSubmit)="save()" class="wallForm">
<div class="row">
<span class="sr-only">Select Wall and Board</span>
</div>
<div class="row">
{{selectedWall.Id}}
<select [(ngModel)]="selectedWall.Id" name="Wall" (change)="wallSelected()">
<option *ngFor="let wall of walls" value={{wall.Id}}>{{wall.Item.Title}}</option>
</select>
</div>
<div class="row">
class="btn active-element btn-lg width-50" *ngIf="itemAction == '0'">
Copy
</button>
<button type="submit" (click)="save()"
class="btn active-element btn-lg width-50" *ngIf="itemAction == '1'">
Move
</button>
</div>
</form>
</div>
Here is the typescript.
import { Component, ViewChild, ElementRef, OnInit, Input } from "@angular/core";
import { Router } from '@angular/router';
//import { MODAL_DIRECTIVES, BS_VIEW_PROVIDERS } from 'js/ng2-bootstrap/bundles/ng2-bootstrap.umd.js';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'movecopy-item',
templateUrl: 'app/components/forms/componentManagement/movecopyForm.component.html'
})
export class movecopyComponent implements OnInit {
@ViewChild('mcFormModal') modal: ModalDirective;
private currentUser: user;
private itemAction: ITEM_ACTION;
private modalTitle: string;
@Input() component: viewItem;
walls: viewItem[];
selectedWall: viewItem;
constructor(private _contentService: ContentService,
private _alertService: AlertService,
private _router: Router) {
}
ngOnInit(): void {
//Get all the walls for the user.
this.walls = [];
this.selectedWall = new viewItem();
this.loadWalls();
}
private loadWalls() {
this._contentService.getAllWalls()
.subscribe(data => this.wallListReceived(data),
error => this.handleError(error));
}
private wallListReceived(data: any) {
this.walls = data;
}
hide() {
this.modal.hide();
}
private wallSelected(): void {
console.log('Selected wall');
console.log(this.selectedWall.Id);
//get boards for the wall.
this.getWallContent();
console.log(this.selectedWall.Id);
}
The {{selectedWall.Id}}
does get updated, but for some reason in the wallSelected
method, this.selectedWall.Id
keeps returning a 0.
What am I doing wrong here? What might be the reason for the value not reflecting here?
The order of events on an element is undefined. You can't expect
ngModel
to update the model before the event handler for thechange
event was processed.Use instead
because
ngModel
only emitsngModelChange
after it updated the model