Is there a way to convert the value of obj.category
into the Category
type as shown in the example below?
I specifically need this conversion in order to select options in a dropdown.
export class Category{
id: number;
name: string;
constructor(obj: any) {
this.id = obj.id;
this.name = obj.name;
}
}
export class Post {
category: Category[];
constructor(obj: any) {
this.category = obj.category;
}
}
The Category service is outlined as follows:
getCategories(): Promise<Category[]> {
return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
.then(response => response.json().map(obj => new Category(obj)))
.catch(this.handleError);
}
This is how the API responds:
[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]
Template:
<select multiple name="category" [(ngModel)]="obj.post.category">
<option *ngFor="let category of categories" [ngValue] = "category">
{{category.name}}
</option>
</select>