[英]Angular 4 - *ngFor with condition to get different value for ngModel
我是angular 4的新手。使用HTML下拉select和option的 * ngFor遇到了問題。
我有類別array-object-
categories = [
{ id:1, title: 'c/c++'},
{ id:2, title: 'JavaScript'},
{ id:3, title: 'Angular'},
{ id:4, title: 'Node'}
];
我想在下拉列表中顯示標題,但我想在ngModel中獲取類別ID。
像-在HTML視圖中的下拉列表中顯示所有標題,但是當我選擇其中一個時,ngModel將獲得該類別ID。
即:我選擇JavaScript,ngModel將獲得JavaScript類別的ID。
我在Google上搜索了很多時間,但找不到任何解決方案。
這是HTML代碼-
<label>Category</label>
<select [(ngModel)]="post.category_id" class="form-control select2" style="width: 100%;">
<option *ngFor="let category of categories">{{ category.title}}</option>
</select>
您可以綁定value
屬性:
<option *ngFor="let category of categories" [value]="category.id">{{ category.title }}</option>
您將必須更新ngModel
變量和option
,如下所示。
<select [(ngModel)]="category_id" class="form-control select2">
<option *ngFor="let category of categories" [value]="category.id"
[innerHtml]=" category.title "></option>
</select>
在您的代碼post.category_id
post
將獲取id的值,然后post.category_id
將給出undefined
。
經過各種嘗試找出您所犯的錯誤.....請先檢查以下幾點
import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http';
@NgModule({ imports: [ BrowserModule,FormsModule, HttpModule ], declarations: [ App ], bootstrap: [ App ] })
<label>Category</label> <select [(ngModel)]="category_id" name="category_id" class="form-control select2" style="width:100%"> <option *ngFor="let category of categories" [value]="category.id">{{ category.title }}</option> </select> <h2>Select Category Id : {{category_id}}</h2>
這些步驟后,您必須獲得所需的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.