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

Angular 4不能绑定到“窗体组”,因为它不是“窗体”的已知属性

蒋高超
2023-03-14
import { Component, Input, OnChanges, SimpleChange } from '@angular/core';
import { FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';

import { HttpClient, HttpErrorResponse } from '@angular/common/http';                                                                                                                                                           


@Component({
  templateUrl: 'ads.component.html'
})
export class AdsComponent {
    form;
    ngOnInit() {
        this.form = new FormGroup({
            ads_name: new FormControl("Hello Ads!")
        });
    } 

  constructor(
    private http: HttpClient
    ) {

   }

   onSubmit = function(user) {
        console.log(user);
   }

}
<form class="form-horizontal" [formGroup] = "form" (ngSubmit)="onSubmit(form.value)">
   <div class="form-group row">
       <label class="col-md-3 form-control-label" for="ads_name">Ads Name</label>
       <div class="col-md-9">
           <input type="text" id="ads_name" name="ads_name" class="form-control" placeholder="Ads Name" formControlName="ads_name" ngModel>
       </div>
   </div>
</form>

下面是我模块中的代码

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

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    BsDropdownModule.forRoot(),
    TabsModule.forRoot(),
    ChartsModule,
    ReactiveFormsModule,
    HttpClientModule,
    FormsModule
  ],

共有1个答案

傅长恨
2023-03-14

正如您的错误所述:

模板分析错误:无法绑定到“窗体组”,因为它不是“窗体”的已知属性。(“][formGroup]=”form“(ngSubmit)=”onSubmit(form.value)“>”):ng:///componentsmodule/adscomponent.html@

我们可以假设您的adscomponentcomponentsmodule声明的一部分,但是您已经在appmodule中导入了reactiveformsmodule。因此,为了使angular能够编译adscomponent的模板,您应该:

1)在componentsmodule中导入reactiveformsmodule:

@NgModule({
  imports: [
    ...
    ReactiveFormsModule
  ]
})
export class ComponentsModule {}

2)或导出ReactiveFormModule的导入模块

@NgModule({
  exports: [
    ...
    ReactiveFormsModule
  ]
})
export class SharedModule {}

@NgModule({
  imports: [
    ...
    SharedModule
  ]
})
export class ComponentsModule {}

另见:

 类似资料: