【问题标题】:select option dosen't show data angular选择选项不显示数据角度
【发布时间】:2020-10-15 06:51:09
【问题描述】:
当我想选择一个选项时,它显示为 blanc 或不显示列表,我不知道为什么或如何解决它
<div class="form-group">
<label for="Categorie">Categorie : </label>
<select class="form-control" name="Categorie" formControlName="Categorie" [(ngModel)]="this.Categorie.id" required>
<option Value="0" disabled > choisir categorie</option>
<option *ngFor="let Categorie of categorieList" [ngValue]="this.Categorie.id" (change)="Selectedvalue($event)">
<h1>{{Categorie.name}}</h1>
</option>
</select>
</div>
【问题讨论】:
标签:
html
angular
forms
spring-boot
【解决方案1】:
使用 ngModel 时不需要表单控制。这是example on Stackblitz,这是代码:
html:
<div class="form-group">
<label for="Categorie">Categorie : </label>
<select class="form-control" name="Categorie" [(ngModel)]="selectedCategory" required>
<option *ngFor="let categorie of categories" [ngValue]="categorie"
(change)="Selectedvalue($event)">
<h1>{{categorie.name}}</h1>
</option>
</select>
</div>
ts:
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
selectedCategory;
categories = [
{ id: 1, name: "cat 1" },
{ id: 2, name: "cat 2" },
{ id: 3, name: "cat 3" }
];
ngOnInit() {
this.selectedCategory = this.categories[2];
}
selectedvalue(item) {
this.selectedCategory = item;
}
}
OnInit,我设置了select的默认值(如果你想在你的html模板中使用deault选项,你可以去掉它)。
当一个item被选中时,我设置在selectedCategory中,也就是select的ngModel。