Reputation: 1385
I have a json object as below :
dataset: Dataset[] = [
{
serviceType: "server Mangemanet",
serviceValues: [
"6.2",
"6.3",
"6.6"
]
},
{
serviceType: "server admin",
serviceValues: [
"4.1",
"4.2",
"4.6"
]
},
];
and i have two drop downs so that the value in thesecond one should be displayed based on the value selected in first dropdown . In first drop down i will select the servicetype and in the second dropdown the corresponding service values should appear. iam trying to do it this way :
<td>
<select [(ngModel)]="data2" placeholder="select a value" (change)="data2 = dataset[idx];" >
<option *ngFor="let data of dataset;let idx = index;" value= {{dataset[idx].serviceType}} >
{{dataset[idx].serviceType}}
</option>
</select>
</td>
<td>
<select placeholder="select a value" [(ngModel)]="data2" >
<option *ngFor="let data of data2.serviceValues;let idx = index" value= {{data}} >
{{data}}
</option>
</select>
</td>
But the error says : Cannot read property 'serviceValues' of undefined at Object.eval I am not able to find why it not able to read service values from the array.
Thanks
Upvotes: 0
Views: 1628
Reputation: 272
Here's a working example:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(){}
data1: any;
data2: any;
dropdown: any[] = []; //the one which will be triggered when first dropdown is selected
dataset: any[] = [
{ serviceType: "server Mangemanet", serviceValues: ["6.2","6.3","6.6"] },
{ serviceType: "server admin", serviceValues: ["4.1","4.2","4.6"] },
];
triggerd2(event: any): void {
this.dropdown = this.dataset.find(item=>{
return item.serviceType == event;
}).serviceValues;
}
}
And the html part:
<td>
<select [(ngModel)]="data1" placeholder="select a value" (change)="triggerd2($event.target.value)" >
<option *ngFor="let data of dataset;let i = index;" value={{data.serviceType}}>
{{data.serviceType}}
</option>
</select>
</td><br />
<td>
<select placeholder="select a value" [(ngModel)]="data2" >
<option *ngFor="let data of dropdown;let idx = index" value= {{data}} >
{{data}}
</option>
</select>
</td>
Try on stackblitz here
Upvotes: 3
Reputation: 8166
Try Using following code :
You have used [(ngModel)]="data2"
2 times. and I have changed (change)
event as well.
<td>
<select [(ngModel)]="data1" placeholder="select a value" (change)="data2 = dataset[$event.target.value];" >
<option *ngFor="let data of dataset;let idx = index;" value= {{idx}}">
{{dataset[idx].serviceType}}
</option>
</select>
</td>
<td *ngIf="data2">
<select placeholder="select a value" [(ngModel)]="data2" >
<option *ngFor="let data of data2.serviceValues;let idx = index" value= {{data}} >
{{data}}
</option>
</select>
</td>
Upvotes: 1