我正在尝试在Angular.JS中创建一个带有验证的简单表单。只是学习如何使用框架。当我将[(ngModel)]添加到我的第一个表单输入时,我丢失了所有的HTML。当我拿出它[(ngModel)]时,所有的html都会返回。这是我的代码:
应用程序/ 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.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.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 { }
是什么造成了这个问题?
答案 0 :(得分:0)
表单模块需要在模块级别导入和提供,而不是在组件级别。您的应用模块应如下所示:
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,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 1 :(得分:0)
我认为,由于[(ngModel)]="user.firstname"
未定义,因此每次添加user.firstname
时都会遇到语法错误。
首先改变你声明这些公共变量的方式:
export class User {
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 = "";
}
你的User
声明也应该改变:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
// make this of type User
user: User;
users: any;
constructor()
{
// init code goes here always
this.user = new User();
this.users = [];
}
onSubmit(){
this.users.push(this.user);
this.user = new User();
}
}
希望有所帮助