当前位置: 首页 > 知识库问答 >
问题:

未捕获的错误:模板分析错误:无法绑定到“FormGroup”,因为它不是“Form”的已知属性

杜经艺
2023-03-14
import { Component, Input, OnChanges, SimpleChange, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  form: FormGroup;
  ngOnInit() {
      this.form = new FormGroup({
        firstname: new FormControl('First Name'),
        lastname: new FormControl(''),
        languages: new FormControl('')
      });
    }

  onSubmit = function(user) {
    console.log(user);
  };
}  
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { MemberComponent } from './member/member.component';
import { ItemListComponent } from './item-list/item-list.component';
import { SortPipe } from './app.sort';

@NgModule({
  declarations: [
    SortPipe,
    AppComponent,
    ProductComponent,
    MemberComponent,
    ItemListComponent
  ],
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }
<form [FormGroup]="form" (ngSubmit)="onSubmit(form.value)">
    <input type="text" placeholder="firstname" name="firstname" formControlName="firstname" />
    <br>
    <input type="text" placeholder="lastname" name="lastname" formControlName="lastname" />
    <br>
    <select name="languages" formControlName="languages">
        <option value="C++">C++</option>
        <option value="Java">Java</option>
        <option value="Angular">Angular</option>
    </select>
    <br><br>
    <input type="submit" value="submit" />
</form>

共有1个答案

严亮
2023-03-14

看来你打错了。

应该是formGroup而不是formGroup:

<form [formGroup]="form"

因为FormGroupDirective看起来像:

@Directive({
  selector: '[formGroup]', 
  ...
})
export class FormGroupDirective extends ControlContainer implements Form,
 类似资料: