我已经有一个正在运行的Angular应用程序,因为有功能扩展,我必须实现应用程序的路由和登录页面。以前没有路由,作为路由的一部分,我添加了以下代码。app.modules.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { SignUpComponent } from './sign-up/sign-up.component';
import { LoginComponent } from './login/login.component';
import {CommonModule} from "@angular/common";
import {FormsModule , ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
SignUpComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
CommonModule,
ReactiveFormsModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
sign-up.componnent.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
@Component({
selector: 'app-sign-up',
templateUrl: './sign-up.component.html',
styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent implements OnInit{
public signupFrom : FormGroup|any;
constructor(private formBuilder: FormBuilder) {}
items : Array<any> = [
{name:"username", type:"text", data:"Username"},
{name:"password", type:"password",data:"Password"},
{name:"email", type:"text",data:"Email"}
]
ngOnInit(): void {
this.signupFrom = new FormGroup({
'Username' : new FormControl(),
'Passoword' : new FormControl(),
'Email' : new FormControl()
})
}
}
sign-up.component.htm
<div class="row">
<div class="mx-auto col-10 col-md-8 col-lg-6">
<!-- Form -->
<form [formGroup]="signupFrom" class="form-example" >
<div *ngFor="let item of items " class="form-group" >
<label for="{{item.name}}">{{item.data}}</label>
<input
type="{{item.type}}"
class="form-control {{item.name}}"
id="{{item.name}}"
placeholder="{{item.data}}..."
name="{{item.data}}"
/>
</div>
<button type="submit" class="btn btn-primary btn-customized mt-4">
Sign Up
</button>
</form>
<!-- Form end -->
</div>
</div>
当我尝试执行ng-serve时,我得到以下错误:无法绑定到“formGroup”,因为它不是“form”的已知属性。
1条答案
按热度按时间h5qlskok1#
我看到代码是正确的,除了一些点:
1.组件中never的模块应该导入。
1.将formGroup声明为:
public signupFrom! : FormGroup
(the!对typeScript说“我知道一开始表单可以是null或undefined”)。1.通常,当我们在app.module.ts中导入一个新模块时,我们需要“重启”NG服务器
1.您应该在.html中使用绑定和formControlName,否则输入不会与formGroup的formControl“连接”。
1.请参阅 *ngIf以避免初始错误
1.注意:要小心,当你创建formGroup时,你就被写入了