【发布时间】:2017-09-01 19:58:29
【问题描述】:
我正在尝试在 Angular.JS 中创建一个带有验证的简单表单。只是学习如何使用框架。当我将 [(ngModel)] 添加到我的第一个表单输入时,我丢失了所有 HTML。当我取出 [(ngModel)] 时,所有的 html 都会返回。这是我的代码:
app/user.ts
export class User {
constructor(
public firstname: string = "",
public lastname: string = "",
public email: string = "",
public password: string = "",
public address: string = "",
public unitaptnumber: string = "",
public city: string = "",
public state: string = "",
public luck: string = "",
){}
}
app/app.component.ts
import { Component } from '@angular/core';
import { User } from './user';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = new User();
users = [];
onSubmit(){
this.users.push(this.user);
this.user = new User();
}
}
app/app.component.html
<h1>Registration</h1>
<h3>Account Information</h3>
<form (submit)="onSubmit()">
First Name <input
type="text"
name="firstname"
required
[(ngModel)]="user.firstname"
#firstname="ngModel"
>
<input type="submit" value="Register">
</form>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
是什么造成了这个问题?
【问题讨论】:
-
你能加你的
app.module.ts -
编辑了我的问题,现在也包括在内。
标签: javascript html forms angular validation