我有一个用户可以创建Todo的表单。 ITodo
具有以下属性:
export interface ITodo {
id: number;
title: string;
priority: ITodoPriority;
}
export interface ITodoPriority {
id: number;
name: string;
}
因此,创建Todo包括设置title
- 属性并从下拉列表中选择priority
。表格如下:
<form (submit)="saveTodo()">
<input type="text" [(ngModel)]="todo.title" />
<br />
<select (change)="setPriority($event.target.value)">
<option *ngFor="let priority of formModel.priorities" [value]="priority" [innerHtml]="priority.name"></option>
</select>
</form>
我的Component
:
@Component({
selector: "[todo-form]",
templateUrl: "todo-form.view.html"
})
export class TodoFormComponent implements OnInit {
private formModel: ITodoFormModel;
private todo: ITodo = {
id: -1,
name: "",
priority: null
};
ngOnInit() {
//Retrieve formmodel, set in actual code
}
private setPriority(priority: any): void {
this.todo.priority = priority; //This is where the problems is
}
}
问题出在函数setPriority
中,特别是在我尝试设置this.todo.priority
的部分。参数priority
的值可用,但我无法将其设置为this.todo.priority
。
我尝试了什么,以下是什么工作:
private setPriority(priority: any): void {
let p: ITodoPriority = null;
this.formModel.priorities.forEach(function (item) {
if(priority == item) {
p = item;
}
});
this.todo.priority = p;
}
所以,这确实有效,但看起来有点丑陋和低效。 这样做的方法是什么?
答案 0 :(得分:2)
为什么不使用与priority
的双向绑定?此外,由于您使用的是表单,我很惊讶它不会因您在表单中使用name
- 属性而引发错误,但无论如何,请使用双向绑定,并且自{ {1}}是一个对象,要绑定整个对象,请使用priority
。所以你的选择看起来像这样:
[ngValue]
因此,由于您使用的是双向绑定,因此不需要更改事件:)
答案 1 :(得分:0)
尝试这样做:
<select (ngModelChange)="setPriority($event)">
<option *ngFor="let priority of formModel.priorities" [value]="priority" >{{priority.name}}</option>
</select>
如果它不起作用,请告诉您在更改时收到的对象的价值
private setPriority(priority: any): void {
this.todo.priority = priority; //Is this value you are receiving correct?
}