Angular 2 RC5 [(ngModel)] 数据绑定(bind)失败

标签 angular angular2-databinding

我已经看了这段代码一段时间了,但我被卡住了:我有一个绑定(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/

相关文章:

javascript - Angular2 动态按钮一次只能选择一个

angular - 使用模板插值多次调用函数?

Angular - 将组件方法绑定(bind)到 DOM 目标属性是错误的做法吗?

javascript - Angular Material Design - 将日期对象绑定(bind)到 MdDatepicker

Angular 2+ ngFor 中的 NgTemplateOutlet

angular - 排除破坏 Angular Universal 的组件

javascript - 我怎样才能以更有效的方式减少它

angular - 以 Angular 订阅后如何执行某些操作