development

'form'의 알려진 속성이 아니므로 'formGroup'에 바인딩 할 수 없습니다.

big-blog 2020. 10. 2. 22:57
반응형

'form'의 알려진 속성이 아니므로 'formGroup'에 바인딩 할 수 없습니다.


그 상황:

도와주세요! Angular2 앱에서 매우 간단한 형식을 만들려고 노력하고 있지만 작동하지 않는 것이 무엇이든 상관 없습니다.

ANGULAR 버전 :

각도 2.0.0 Rc5

오류:

Can't bind to 'formGroup' since it isn't a known property of 'form'

여기에 이미지 설명 입력

코드:

보기:

<form [formGroup]="newTaskForm" (submit)="createNewTask()">

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name" required>
    </div>

     <button type="submit" class="btn btn-default">Submit</button>

</form>

컨트롤러 :

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';

@Component({
    selector: 'task-add',
    templateUrl: 'app/task-add.component.html'

})


export class TaskAddComponent {

    newTaskForm: FormGroup;

    constructor(fb: FormBuilder) 
    {
        this.newTaskForm = fb.group({
            name: ["", Validators.required]
        });
    }

    createNewTask()
    {
        console.log(this.newTaskForm.value)
    }

}

ngModule :

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

import { routing }        from './app.routing';
import { AppComponent }  from './app.component';
import { TaskService } from './task.service'


@NgModule({
    imports: [ 
        BrowserModule,
        routing,
        FormsModule
    ],
    declarations: [ AppComponent ],
    providers: [
        TaskService
    ],
    bootstrap: [ AppComponent ]
})


export class AppModule { }

질문:

왜 그 오류가 발생합니까?

내가 뭔가를 놓치고 있습니까?


RC5 수정

당신은 할 필요가 import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'컨트롤러에 그리고 추가 directives에서 @Component. 그러면 문제가 해결됩니다.

이를 수정 한 후 formControlName="name"양식에 입력을 추가하지 않았기 때문에 다른 오류가 발생할 수 있습니다.

RC6 / RC7 / 최종 릴리스 FIX

이 오류를 수정하려면 모듈에서 가져 오기만 ReactiveFormsModule하면 @angular/forms됩니다. 다음은 ReactiveFormsModule가져 오기 가있는 기본 모듈의 예입니다 .

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';

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

export class AppModule { }

더 설명하기 위해 는의 일부인 formGroup지시문에 대한 선택기 이므로 가져와야합니다. 기존 항목 을 DOM 요소 에 바인딩하는 데 사용됩니다 . Angular의 공식 문서 페이지 에서 더 많은 것을 읽을 수 있습니다 .FormGroupDirectiveReactiveFormsModuleFormGroup


기능 모듈 과 결합 된 Angular 4 (예를 들어 공유 모듈을 사용하는 경우)를 사용하려면를 내 보내야합니다 ReactiveFormsModule.

import { NgModule }                                 from '@angular/core';
import { CommonModule }                             from '@angular/common';
import { FormsModule, ReactiveFormsModule }         from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { } 

약간의 파고를 한 후 " 'form'의 알려진 속성이 아니기 때문에 'formGroup'에 바인딩 할 수 없습니다."에 대한 해결책을 찾았습니다.

제 경우에는 여러 모듈 파일을 사용하고 있으며 app.module.ts에 ReactiveFormsModule을 추가했습니다.

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

@NgModule({
  declarations: [
    AppComponent,
  ]
  imports: [
    FormsModule,
    ReactiveFormsModule,
    AuthorModule,
],
...

하지만 다른 모듈에 추가 된 구성 요소에서 [formGroup] 지시문을 사용할 때는 작동하지 않았습니다. 예를 들어 author.module.ts 파일에 구독 된 author.component.ts의 [formGroup]을 사용하는 경우 :

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
import { AuthorComponent } from './author.component';

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
    AuthorComponent,
  ],
  providers: [...]
})

export class AuthorModule {}

app.module.ts에 ReactiveFormsModule을 추가하면 기본적으로 ReactiveFormsModule 이이 경우 author.module과 같은 모든 하위 모듈에 상속 될 것이라고 생각했습니다 ... (틀 렸습니다!). 모든 지시문이 작동하도록하려면 author.module.ts에서 ReactiveFormsModule을 가져와야했습니다.

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

@NgModule({
  imports: [
    ...,
    FormsModule,    //added here too
    ReactiveFormsModule //added here too
  ],
  declarations: [...],
  providers: [...]
})

export class AuthorModule {}

따라서 하위 모듈을 사용하는 경우 각 하위 모듈 파일에서 ReactiveFormsModule을 가져와야합니다. 이것이 누구에게나 도움이되기를 바랍니다.


구성 요소의 단위 테스트 중에이 오류가 발생했습니다 (테스트 중에 만 응용 프로그램 내에서 정상적으로 작동 함). 해결책은 파일 로 가져 오는 것 ReactiveFormsModule입니다 .spec.ts.

// Import module
import { ReactiveFormsModule } from '@angular/forms';

describe('MyComponent', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            imports: [ReactiveFormsModule],  // Also add it to 'imports' array
        })
        .compileComponents();
    }));
});

대신 나는 다른 방법으로 사용했다 제안 대답은 각도 (4)와 함께 나를 위해 작동하지 않았다 바인딩 속성attr접두사를 :

<element [attr.attribute-to-bind]="someValue">

두 개의 모듈을 가져와야하는 경우 다음과 같이 추가하십시오.

import {ReactiveFormsModule,FormsModule} from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent,
    HomeComponentComponent,
    BlogComponentComponent,
    ContactComponentComponent,
    HeaderComponentComponent,
    FooterComponentComponent,
    RegisterComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

"기능 모듈"을 정의한 경우 이미 .NET Framework로 가져온 경우에도 기능 모듈에서 가져와야합니다 AppModule. Angular 문서에서 :

모듈은 다른 모듈에서 선언 된 구성 요소, 지시문 또는 파이프에 대한 액세스 권한을 상속하지 않습니다. AppModule이 가져 오는 것은 ContactModule과 무관하며 그 반대의 경우도 마찬가지입니다. ContactComponent가 [(ngModel)]과 바인딩하기 전에 ContactModule이 FormsModule을 가져와야합니다.

https://angular.io/docs/ts/latest/guide/ngmodule.html


Angular 7에서 동일한 문제가 발생했습니다. app.module.ts 파일에서 다음을 가져옵니다.

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

그런 다음 FormsModule 및 ReactiveFormsModule을 가져 오기 배열에 추가하십시오.

imports: [
  FormsModule,
  ReactiveFormsModule
],

이 문제는 FormsModule, ReactiveFormsModule 가져 오기가 누락되어 발생합니다. 동일한 문제가 발생했습니다. 내 사건은 다르다. 모듈로 작업하고 있었기 때문에 부모 모듈에서 위의 가져 오기를 놓쳤지만 하위 모듈로 가져 왔지만 작동하지 않았습니다.

그런 다음 아래와 같이 부모 모듈로 가져 왔고 작동했습니다!

import { ReactiveFormsModule,FormsModule  } from '@angular/forms';
import { AlertModule } from 'ngx-bootstrap';

         @NgModule({
          imports: [
            CommonModule,
            FormsModule,
            ReactiveFormsModule,
    ],
      declarations: [MyComponent]
    })

이 오류에 대해 이러한 스레드를 살펴 보는 사람들을 위해. 제 경우에는 FormsModule과 ReactiveFormsModule 만 내보내고 가져 오는 것을 잊은 공유 모듈이 있습니다. 이로 인해 양식 그룹이 하위 구성 요소에서 작동하지 않는 이상한 오류가 발생했습니다. 사람들이 머리를 긁는 데 도움이되기를 바랍니다.


e2e 테스트를 시도 할 때이 오류가 발생했고 이에 대한 답변이 없다는 사실이 저를 미치게 만들었습니다.

테스트를하는 경우 * .specs.ts 파일을 찾아 다음 을 추가합니다.

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

참고 : 로더에주의하고 최소화하십시오 (Rails env.) :

이 오류를보고 모든 솔루션을 시도한 후 HTML 로더에 문제가 있음을 깨달았습니다.

이 로더 ( config/loaders/html.js.)를 사용 하여 구성 요소의 HTML 경로를 성공적으로 가져 오도록 Rails 환경을 설정했습니다 .

module.exports = {
  test: /\.html$/,
  use: [ {
    loader: 'html-loader?exportAsEs6Default',
    options: {
      minimize: true
    }
  }]
}

몇 시간의 노력과 수많은 ReactiveFormsModule 가져 오기 후 나는 내 formGroup편지가 formgroup.

이것은 나를 로더로 이끌었고 최소화시 HTML을 축소했다는 사실을 알게되었습니다.

옵션을 변경 한 후에는 모든 것이 제대로 작동했고 다시 울기 시작했습니다.

I know that this is not an answer to the question, but for future Rails visitors (and other with custom loaders) i think this could be helpfull.


using and import REACTIVE_FORM_DIRECTIVES:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';

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

export class AppModule { }

If you have this problem when you developing a component so you should add these two modules to your closest module :

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
   // other modules
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And if you are developing a test for your components so you should add this module to your test file like this:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ContactusComponent } from './contactus.component';
import { ReactiveFormsModule } from '@angular/forms';

describe('ContactusComponent', () => {
  let component: ContactusComponent;
  let fixture: ComponentFixture<ContactusComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ContactusComponent],
      imports:[
        ReactiveFormsModule
      ]

    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ContactusComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Import and register ReactiveFormsModule in your app.module.ts.

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

@NgModule({
declarations: [
AppComponent,
HighlightDirective,
TestPipeComponent,
ExpoentialStrengthPipe

],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Make sure your spelling is correct in both .ts and .html file. xxx.ts

  profileForm = new FormGroup({
  firstName: new FormControl(''),
 lastName: new FormControl('')
 });

xxx.html file-

  <form [formGroup]="profileForm"> 
  <label>
  First Name:
   <input type="text" formControlName = "firstName">
  </label>

  <label>
  Last Name:
   <input type="text" formControlName = "lastName">
   </label>
   </form>

I was by mistake wrote [FormGroup] insted of [formGroup]. Check your spelling correctly in .html. It doesn't throw compile time error If anything wrong in .html file.


Can't bind to 'formGroup' since it isn't a known property of 'form'

angular ( [prop])를 사용하여 속성을 바인딩하려고 하지만 angular는 해당 요소 (이 경우 form) 에 대해 아는 것을 찾을 수 없습니다 .

이는 올바른 모듈을 사용하지 않고 (어딘가에 가져 오기가 누락 됨) 발생할 수 있으며 때로는 다음과 같은 오타가 발생할 수 있습니다.

[formsGroup], s이후form


나처럼 바보 같이 굴지 마 위와 동일한 오류가 발생했습니다.이 스레드의 옵션 중 아무것도 작동하지 않았습니다. 그런 다음 FormGroup에서 'F'를 대문자로 사용했음을 깨달았습니다. 도!

[FormGroup]="form" 

모듈을 AppModule모든 것에 추가하면 정상적으로 작동하기 시작했습니다.

참고 URL : https://stackoverflow.com/questions/39152071/cant-bind-to-formgroup-since-it-isnt-a-known-property-of-form

반응형