Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度预选选项_Angular_Select_Option - Fatal编程技术网

Angular 角度预选选项

Angular 角度预选选项,angular,select,option,Angular,Select,Option,加载组件时,我需要用变量值预填充选项下拉菜单的第一个值。(该值来自db,但为了简化我手动填充的所有内容。)通过ngFor循环数组动态加载选项。我希望第一个选项是firstColor的值 组成部分: import { Component, VERSION } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html&

加载组件时,我需要用变量值预填充选项下拉菜单的第一个值。(该值来自db,但为了简化我手动填充的所有内容。)通过
ngFor
循环数组动态加载选项。我希望第一个选项是
firstColor
的值

组成部分:

import { Component, VERSION } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;

  firstCar: String = "";
  colors: any[] = [];
  firstColor: any[] = [];
  ngOnInit() {
    this.firstCar = "audi";

    this.firstColor = [
      {
        name: "bianco",
        code: "#ffffff"
      }
    ];

    this.colors = [
      {
        name: "rosso",
        code: "#ff0000"
      },
      {
        name: "bianco",
        code: "#ffffff"
      },
      {
        name: "nero",
        code: "#000000"
      }
    ];
  }
}
模板

primo-esempio
选择一辆车:
沃尔沃汽车
萨博
梅赛德斯
奥迪
第二埃森皮奥酒店
选择一种颜色:
{{c.code}}

尝试以下方法:

<select name="colors" id="colors">
  <option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor[0].name" >
    {{c.code}}
  </option>
</select>

{{color['code']}
<select name="colors" id="colors">
  <option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor.name" >
    {{c.code}}
  </option>
</select>
<select name="colors" id="colors">
  <option *ngFor="let color of colors" [selected]="color['name'] === this.firstColor[0]['name']" >
    {{color['code']}}
  </option>
</select>