Javascript 角度2-示例代码-定义的模型属性未定义
尝试按照Angular 2教程中的连接窗体的示例进行操作。我正在修改登录页面的代码。 这是我的模型Javascript 角度2-示例代码-定义的模型属性未定义,javascript,angular,Javascript,Angular,尝试按照Angular 2教程中的连接窗体的示例进行操作。我正在修改登录页面的代码。 这是我的模型 export class LoginModel { constructor( public id: number, public password: string ) {} } 这是我的组件 import { Component, OnInit } from "@angular/core"; import { LoginModel } from "../Mod
export class LoginModel {
constructor(
public id: number,
public password: string
) {}
}
这是我的组件
import { Component, OnInit } from "@angular/core";
import { LoginModel } from "../Models/login.model";
@Component({
selector: "login-form",
templateUrl: "views/login.component.html",
})
export class LoginComponent implements OnInit {
model = new LoginModel(111, "true");
submitted = false;
ngOnInit() {
this.model.id = 111;
this.model.password = "true";
}
onSubmit(): void {
this.submitted = true;
}
// remove - used for debugging
get diagnostic(): string {
return "HERE: " + JSON.stringify(this.model);
}
}
组件中的OnInit可能不需要,我只是想尝试一下
最后是我的HTML
<div class="container">
<h1>Login Form</h1>
{{diagnostic}}
<form *ngIf="model">
<div class="form-group col-md-6">
<label for="id">User ID:</label>
<input type="text" class="form-control" id="id" name="id"
required
[(ngModel)]="model.id"
>
</div>
<div class="form-group col-md-6">
<label for="password">Password</label>
<input type="text" class="form-control" id="password" name="password"
required
[(ngModel)]="model.password"
>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
登录表单
{{diagnostic}}
用户ID:
密码
提交
我经常遇到的错误是“model.id”未定义。为了验证这一点,我添加了*ngIf=“model”。我不确定为什么模型在通过我的模块导入的LoginComponent中定义时显示为未定义
如果您能提供任何帮助,我将不胜感激。我已经在这一点上停留了一段时间,在网上搜索时没有找到任何有用的东西。我们没有所有的代码,但我认为您可能没有导入所有必要的模块。您似乎缺少
FormsModule
和ReactiveFormsModule
这是我根据上面提供的代码创建的plunker,我在空白处填写了缺少的
NgModule
定义:好的,谢谢您的帮助。我正在导入FormsModule,添加ReactiveFormsModule没有任何区别。我认为在我的VisualStudio中设置的环境可能有一些根本性的问题。我将尝试进行一次全新的安装/创建一个新项目,看看这是否解决了任何问题。谢谢奇迹般的是,今天早上我启动了我的电脑,决定再试一次这个老项目,它就这样工作了。老实说,除了VisualStudio被搞得一团糟之外,我无法解释为什么它以前失败了。再次感谢。很高兴听到它起作用了。我最近在IntelliJ中遇到了一些问题,这些问题似乎指向IDE的缓存,因为清除缓存并重新启动它似乎会迫使IntelliJ重新编制索引。