我已经看了这段代码一段时间了,但我被卡住了:我有一个绑定(bind)到组件模型的表单和 [(ngModel)]
绑定(bind)中断页面 - 页面不会呈现。我没有收到编译错误和运行时调试器错误,但页面不会呈现。
在此页面上,模型似乎工作正常 - 我可以使用 {{todo.title}}
看到模型值正常,但是当我尝试使用 [ 将值绑定(bind)到表单控件时(ngModel)]="todo.title"应用程序中断。
这是表格:
<form name="form1" id="form1" novalidate>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-bookmark"></i> </span>
<input class="form-control"
name="title"
[(ngModel)]="todo.title"
placeholder="Enter the title for this ToDo"
required >
</div>
</div>
</form>
和 super 简单的组件:
import { Component } from '@angular/core';
import { ToDo } from './todo';
import { ToDoListComponent } from './todo-list';
@Component({
selector: 'todo-entry',
templateUrl: 'app/todo-entry.html'
})
export class ToDoEntryComponent {
todo:ToDo = new ToDo();
new() {
this.todo = new ToDo();
}
}
和:
从“@angular/core”导入{组件};
@Component({})
export class ToDo {
title:string = "new todo";
entered:Date = new Date();
}
如果我使用该代码(无论如何都是一种方式):
value="{{todo.title}}"
我很确定模块加载和组件引用都是正确的,因为只要我不使用 [(ngModel)],其他一切都按预期显示模型值。
知道我在这里遗漏了什么吗?
最佳答案
我认为问题是 Angular 看到你的 [(ngModel)]
并认为你正在尝试使用 Angular 形式,但没有其他支持指令。我不知道为什么你没有得到有用的错误描述。
如果我创建一个使用 ngModel
绑定(bind)但不否则使用 Angular 形式的简单表单,我会收到此错误:
Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first"> Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
所以你可以按照错误所说的去做,并将 [ngModelOptions]="{standalone: true}"
添加到你的控件中,或者你可以使用毯子 ngNoForm
你的 form
元素:
<form name="form1" id="form1" novalidate noNoform>
关于Angular 2 RC5 [(ngModel)] 数据绑定(bind)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197501/