选择选项不显示角度数据

时间:2020-06-24 22:03:16

标签: html angular forms spring-boot

当我想要选择一个显示空白或不显示列表的选项时,我不知道为什么或如何解决此问题

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

1 个答案:

答案 0 :(得分:0)

使用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选项,可以将其删除)。

选中某项后,我将其设置为selectedCategory,即选中项的ngModel。