Angular2 - 填充下拉框/组合框列表

3

我有一个叫做“week-selector”的组件。该组件的目的是允许用户选择他们希望使用或查看的一周。

我对angular还不熟悉,虽然理解了逻辑,但我在向下拉列表中添加选项时遇到了问题。以下代码显示在页面上,但框中没有任何选项。

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

export class DropdownValue {
value:string;
label:string;

constructor(value:string,label:string) {
this.value = value;
this.label = label;
 }
}

@Component({
selector: 'app-week-selector',
template:
`
<form class = "ui small form segment">
<div id="WeekSubmission">
<h1> Please enter the week you are in: </h1>

<select>
<option> *ngFor="value of values" (click)="selectItem(value.value)">    {{value.label}}"> 
{{value}}
</option>
</select>

</div>
</form>
`
})

export class WeekSelectorComponent implements OnInit {
values:DropdownValue[];

@Output()
select:EventEmitter<string>;

constructor() {
this.values = [ new DropdownValue('Team','Liverpool')];
this.select = new EventEmitter();
}

selectItem(value){
 this.select.emit(value)
}

ngOnInit() {
 }

}
2个回答

4

对于单向绑定,您可以使用以下方法来监视选择更改而不仅仅是点击: 我假设您希望在UI中显示value.label并将其记录为值。根据您的要求,您可以更改此值。

<select (change)="selectItem($event.target.value)">
    <option *ngFor="let value of values" value={{value.label}}>{{value.label}}</option>
</select>

// code
selectItem(value){
 this.select.emit(value)
}

对于双向数据绑定,您可以使用以下方法:

<select [ngModel]="selectedValue" (ngModelChange)="selectItem($event)">
    <option [value]="value.label" *ngFor="let value of values">{{value.label}}</option>
</select>

要详细了解Angular中的数据绑定类型,请阅读我的这篇文章

你是不是指的是value={{value.value}}? - Force444

2
如果您的代码是精确的复制粘贴,请考虑删除HTML模板中option标签中多余的>
我个人认为应该这样做:
<option *ngFor="value of values" (click)="selectItem(value.value)">
{{value.label}}
</option>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接