I am trying to change the contents of a drop down list by selecting a different drop down list. The HTML code is as follows.
<div class="form-row">
<div class="form-group col-md-6">
<label for="makesel">Make</label>
<select [ngModel]="vehicle.makeId" class="form-control" id="makesel" (ngModelChange)="onChangeMake($event.target.value)">
<option>Choose a make</option>
<option *ngFor="let make of makes" [value]="make.id">{{ make.name }}</option>
</select>
</div>
<div *ngIf="currentMake" class="form-group col-md-6">
<label for="make">Model</label>
<select [ngModel]="vehicle.modelId" class="form-control" id="model">
<option>Choose a model</option>
<option *ngFor="let model of currentMake.models" value="{{ model.id }}">{{ model.name }}</option>
</select>
</div>
</div>
And the component is encoded as follows:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'register-form',
templateUrl: './registerform.component.html'
})
export class RegisterFormComponent{
public makes: Make[];
public currentMake: Make;
public vehicle: Vehicle;
constructor(http: Http, @Inject('BASE_URL') baseUrl: string){
http.get(baseUrl + 'api/makes').subscribe(result => {
this.makes = result.json() as Make[];
}, error => console.error(error));
this.vehicle = new Vehicle();
};
onChangeMake(makeId : number){
console.log("test");
this.currentMake = this.makes.filter(x => x.Id == makeId)[0];
}
}
class Make {
Id: number;
Name: string;
Models: Model[];
}
class Model{
Id: number;
Name: string;
}
class Vehicle{
makeId : number;
modelId : number;
registered: boolean;
features: number[];
contactName: string;
contactPhone: string;
contactEmail: string;
}
The problem is that the change event is not working anyway, I'm trying. Current code uses ngModel and ngModelChange, but I also tried to use only
change="onChangeMake($event.target.value)"
But I, too, was not successful. It looks like the "onChangeMake" method has not been called. Since I have not found other ways to do this other than these two, and none of them work, I ask for some help. Did I miss something?
For reference: Angular version: 4.2.5 TypeScript version: 2.6.2
Thanks in advance for your reply!
source
share