Reputation: 872
I am working with angular and have cascading selects
city: {};
area: {};
selectedAreas: [];
selectedSuburbs: [];
arrAddress = [{
city: "Auckland",
id: 1,
areas: [{
area: "Waitakere",
id: 11,
suburbs: [{
suburb: "Rodney",
id: 12
},
{
suburb: "North Shore",
id: 13
},
{
suburb: "City",
id: 14
},
]
}]
}];
onSelectCity(e) {
this.city = this.arrAddress.find(element => element.id === Number(e.value));
this.selectedAreas = this.city['areas'];
}
onSelectArea(e) {
this.area = this.selectedAreas.find(element => element.id === Number(e.value));
this.selectedSuburbs = this.area['suburbs'];
}
In the function onSelectArea
I am getting an error on element.id
"[ts] Property 'id' does not exist on type 'never'."
Any ideas? Thanks in advance
Upvotes: 1
Views: 11567
Reputation: 39432
Adding on the top of Jeto's answer:
You might want to specify the types of element
as any
in the callbacks to the find
method to avoid any compilation errors:
import { Component } from '@angular/core';
@Component({...})
export class AppComponent {
city = {};
area = {};
selectedAreas: any[] = [];
selectedSuburbs: any[] = [];
arrAddress = [...];
onSelectCity(e) {
this.city = this.arrAddress.find((element: any) => element.id === Number(e.value));
this.selectedAreas = this.city['areas'];
}
onSelectArea(e) {
this.area = this.selectedAreas.find((element: any) => element.id === Number(e.value));
this.selectedSuburbs = this.area['suburbs'];
}
}
And in your Template:
<select (change)="onSelectCity($event.target)">
<option value="null">Select a City</option>
<option *ngFor="let city of arrAddress" [value]="city.id">{{ city.city }}</option>
</select>
<br><br>
<select (change)="onSelectArea($event.target)" [disabled]="!selectedAreas">
<option value="null">Select an Area</option>
<option *ngFor="let area of selectedAreas" [value]="area.id">{{ area.area }}</option>
</select>
Here's a Sample StackBlitz for your ref
Upvotes: 1
Reputation: 14927
That error you're getting from the compiler is due to selectedAreas
not being declared properly. By doing property: []
you define a property that can only hold an empty array.
Use the following instead, which sets the default value (as opposed to the type):
selectedAreas = []; // note the equal sign
Or better yet:
selectedAreas: Area[] = [];
where Area
would be a class where you define its properties.
You also have the same issue for your other properties (property: {}
defines a property that can only be an empty object).
Upvotes: 10