首页 文章

ngFor和(click)事件Angular 2

提问于
浏览
0

我正在使用带有Typescript的Angular 2 RC4 . 我的问题是:当我点击所需对象的名称时,我想从对象数组中获取一个对象 . 我的代码是:

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);
    }
}

我的HTML代码是:

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

我看了consol日志,我没有看到ClientData.ComponentCategory值,我试图设置一个断点,当我到达它时应用程序永远不会停止 . 所以我想我从不调用getSingleCategory函数 . 有什么建议吗?提前致谢 .

2 回答

  • 0

    不要在 <option> 上使用 (click) .

    而是在 <select> 元素上设置 (change) ,以便在值更改时得到通知,并使用 [(ngModel)]="selectedValue" 轻松获取当前值:

    <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;
        // ...
    }
    
  • 2

    他们在选择选项时需要 (change) 事件 .

    <option *ngFor="let category of ServerCategorys" (change)="getSingleCategory(category)">
        {{category?.CategoryName}}
    </option>
    

相关问题