Reputation: 175
I'm using Angular 2 RC4 with Typescript. My problem is thant: I want to get an object from the array of objects when I click on the name of the needed object. My ts code is:
import { CategoryClass } from '../../category/class/category.class';
import { ComponentClass } from '../class/component.class';
@Component({
templateUrl: './app/inventory/component/add/add.component.html'
})
export class AddComponent {
private ClientData: ComponentClass = {
ComponentId: 0,
ComponentCategory: 0
};
private ServerCategorys: CategoryClass[] = [
{ CategoryId: 0, CategoryName: 'N/A', CategoryNote: 'N/A' }
];
private getSingleCategory(_category: CategoryClass): void {
this.ClientData.ComponentCategory = _category.CategoryId;
console.log(this.ClientData.ComponentCategory);
}
}
My HTML code is:
<div class="form-group row">
<label for="exampleSelect1" class="col-xs-2 col-form-label">Category</label>
<div class="col-xs-10">
<select class="form-control" id="exampleSelect1">
<option></option>
<option *ngFor="let category of ServerCategorys" (click)="getSingleCategory(category)">{{category?.CategoryName}}</option>
</select>
</div>
I watched the consol log and I didn't saw the ClientData.ComponentCategory value, I tryed to put an break point and the application never stoped when I arrived to it. So I suppose that I never call the getSingleCategory function. Any suggestion? Thanks in advance.
Upvotes: 0
Views: 3330
Reputation: 345
You want the (change)
event when they select an option.
<option *ngFor="let category of ServerCategorys" (change)="getSingleCategory(category)">
{{category?.CategoryName}}
</option>
Upvotes: 0
Reputation: 96891
Don't use (click)
on <option>
.
Instead set (change)
on <select>
element just to be notified when the value changes and also use [(ngModel)]="selectedValue"
to easily get the current value:
<select class="form-control" id="exampleSelect1" [(ngModel)]="selectedValue" (change)="getSingleCategory()">
<option *ngFor="let category of ServerCategorys" [value]="category">{{category?.CategoryName}}</option>
</select>
export class AddComponent {
selectedValue = null;
// ...
}
Upvotes: 3