如何在角度6中使用循环选择下拉列表?

Abh*_*ngh 5 angular angular6

我有一个数组作为集合,我想将其加载到下拉列表中,并希望在某种情况下进行默认选择,但我不知道该如何实现。

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-commingsoon',
  templateUrl: './commingsoon.component.html',
  styleUrls: ['./commingsoon.component.css']
})
export class CommingsoonComponent implements OnInit {
  public collection = [];
  constructor() {
    for(let i = 1; i<=10 ; i++) {
      this.collection.push(`Angular: ${i}`);
    }
   }

  ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<select name="" id="" style="position:relative; left: 100px">
    <option *ngFor="let i of collection;" value="{{i}}" [selected]="i == Angular: 2">{{ i }}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我希望下拉列表应为i == Angular:2时的选定值

Icy*_*ool 8

这是一种典型的使用方式ngModel 如果您要在之后处理选定的值,这会更方便。

<select [(ngModel)]="selectedValue">
  <option *ngFor="let option of options" [value]="option.id">
    {{option.name}}
  </option>
</select>
Run Code Online (Sandbox Code Playgroud)

https://stackblitz.com/edit/angular-njs3tz


Bol*_*and 5

缺少引号,请尝试 i == 'Angular: 2'

或者,如果您只对索引感兴趣:

<option *ngFor="let i of collection; let j = idx" value="{{i}}" [selected]="j === 2">{{ i }}</option>