Daniel Zarioiu Daniel Zarioiu - 11 months ago 101
TypeScript Question

ngFor and (click) event Angular 2

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';

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;

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 *ngFor="let category of ServerCategorys" (click)="getSingleCategory(category)">{{category?.CategoryName}}</option>

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.

Answer Source

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>

export class AddComponent {
    selectedValue = null;
    // ...