在下拉列表中显示列表

时间:2018-10-31 12:20:42

标签: angular typescript angular6

我想使用Angular在下拉列表中显示列表。我试图实现这一点:

TypeScript:

构造函数

export class Merchant {
  constructor(
    public id: string,
    public name: string
  ) {}
}

组件:

import {Merchant} from "../domain/merchant";
import {MerchantService} from "../service/merchant.service";

@Component({
  selector: 'app-terminal',
  templateUrl: './terminal.component.html',
  styleUrls: ['./terminal.component.scss']
})
export class TerminalComponent implements OnInit {    
 . ..........
 constructor(private terminalService: TerminalService,
              private merchantService: MerchantService,
              private router: Router,
              private route: ActivatedRoute) {
  }      
  merchants: Merchant[];     
  ngOnInit() {       
    this.route.params.pipe(
      flatMap(params => {
        if (params['id']) {
          return this.terminalService.get(params['id']);
        } else {
          return of(null);
        }
      })
    ......   
  }    
}

HTML代码:

<div class="form-group type">
    <div class="input-group-prepend">
      <label for="type">Merchant</label>
    </div>
    <select class="custom-select" name="type" [(ngModel)]="terminal" id="type" required>
      <option selected></option>
      <option [value]="type" *ngFor="let merchant of merchants">{{merchant.name}}</option>
    </select>
  </div>

我得到空的下拉菜单。你知道我错了吗?

1 个答案:

答案 0 :(得分:1)

您正在迭代空商家数组上的选项,并且也未初始化,因此 您没有选择的项目。例如,尝试:

merchants: Array<Merchant> = [{name:'test' , id:'test'}];