TS和HTML之间的FormGroup绑定

问题描述

我第一次尝试在Angular中创建一个反应式表单

这是代码

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormControl } from "@angular/forms";

@Component({
  selector: 'app-username-password',templateUrl: './username-password.component.html',styleUrls: ['./username-password.component.scss']
})
export class UsernamePasswordComponent implements OnInit {

  loginForm = new FormGroup({
    userName : new FormControl("Ashish"),password : new FormControl("")

  });

  // constructor() { }

  ngOnInit() {
  }

}

和HTML

<div class="container">
    <h2>Login Form</h2>
    <form [formGroup]="loginForm">
        <label> User Name</label>
        <input formControlName="userName",type="text",class="form-control">
    </form>
    {{loginForm.value | json}}
</div>

HTML没有显示任何内容

其中有错误吗?

我在评论中收到此错误

enter image description here

关于, 灰烬

解决方法

您需要将ReactiveFormsModule导入组件所在的AppModule或特定模块中

例如:

...

import { FormsModule,ReactiveFormsModule } from '@angular/forms';

...

@NgModule({
  imports: [
    ...,ReactiveFormsModule,...,],declarations: [...],bootstrap: [AppComponent]
})
export class AppModule {}
,
import { Component,OnInit } from '@angular/core';
import { FormGroup,FormControl } from "@angular/forms";

@Component({
  selector: 'app-username-password',templateUrl: './username-password.component.html',styleUrls: ['./username-password.component.scss']
})

export class UsernamePasswordComponent implements OnInit {

  loginForm: FormGroup;

  // constructor() { }

  ngOnInit() {
        this.loginForm = new FormGroup({
          userName : new FormControl("Ashish"),password : new FormControl("")
        });
  }

}
,

从错误中看来,您似乎没有将ReactiveFormsModule导入包含此组件的模块中。

,

您应像这样将ReactiveFormsModule添加到app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';



@NgModule({
  imports:      [ BrowserModule,ReactiveFormsModule],declarations: [ AppComponent ],bootstrap:    [ AppComponent ]
})
export class AppModule { 

}