Programing

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

lottogame 2020. 9. 27. 12:37
반응형

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


구성 요소가 표시되지 않더라도 Angular 앱을 시작할 때 다음 오류가 발생합니다.

<input>내 앱이 작동하도록 주석 처리해야 합니다.

    zone.js:461 Unhandled Promise rejection: Template parse errors:
    Can't bind to 'ngModel' since it isn't a known property of 'input'. ("
        <div>
            <label>Created:</label>
            <input  type="text" [ERROR ->][(ngModel)]="test" placeholder="foo" />
        </div>
    </div>"): InterventionDetails@4:28 ; Zone: <root> ; Task: Promise.then ; Value: 

Hero plunker를보고 있지만 내 코드와 차이가 없습니다.

다음은 구성 요소 파일입니다.

    import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
    import { Intervention } from '../../model/intervention';

    @Component({
        selector: 'intervention-details',
        templateUrl: 'app/intervention/details/intervention.details.html',
        styleUrls: ['app/intervention/details/intervention.details.css']
    })

    export class InterventionDetails
    {
        @Input() intervention: Intervention;

        public test : string = "toto";
    }

예, app.module.ts에서 방금 추가했습니다.

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

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

양식 입력에 양방향 데이터 바인딩을 사용하려면 모듈 에서 FormsModule패키지 를 가져와야합니다 Angular. 자세한 내용은 여기Angular 2 공식 자습서 양식에 대한 공식 문서를 참조하십시오.


사용의 경우 [(ngModel)]각도 2 , 45 + , 당신은 수입에 필요한 FormsModule 코너 양식에서 ...

또한 그것은의 형태에서이 경로에 각도의 repo 에서 GitHub의 :

각도 / 패키지 / 양식 / src / 지시문 / ng_model.ts

아마도 이것은 AngularJs 개발자 에게는 이전에 ng-model을 언제 어디서나 사용할 수 있었기 때문에 그다지 즐거움이 아니지만 Angular가 그 당시 사용하고 싶은 것을 사용하기 위해 모듈을 분리하려고 시도함에 따라 ngModel이제 FormsModule에 있습니다. .

또한 ReactiveFormsModule 을 사용하는 경우에도 가져와야합니다.

따라서 app.module.ts찾아서FormsModule 가져 왔는지 확인하십시오 .

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule //<<<< and here
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

또한이 Angular4에 대한 의견 시작하는 전류 ngModelFormsModule는 :

/**
 * `ngModel` forces an additional change detection run when its inputs change:
 * E.g.:
 * ```
 * <div>{{myModel.valid}}</div>
 * <input [(ngModel)]="myValue" #myModel="ngModel">
 * ```
 * I.e. `ngModel` can export itself on the element and then be used in the template.
 * Normally, this would result in expressions before the `input` that use the exported directive
 * to have and old value as they have been
 * dirty checked before. As this is a very common case for `ngModel`, we added this second change
 * detection run.
 *
 * Notes:
 * - this is just one extra run no matter how many `ngModel` have been changed.
 * - this is a general problem when using `exportAs` for directives!
 */

양식이 아닌 입력을 사용하려면 함께 사용하고 ngModelOptions독립 실행 형을 true로 만들 수 있습니다 .

[ngModelOptions]="{standalone: true}"

자세한 내용 은 Angular 섹션의 ng_model여기에서 확인하세요.


FormsModule을 가져와야합니다.

app.module.ts 열기

라인 추가

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

@NgModule({
imports: [
   FormsModule
],
})

이것을 던지면 누군가를 도울 수 있습니다.

AuthModule인증 요구를 처리하는 데 전념 하는 새로운 NgModule을 만들었다 고 가정하면 FormsModule해당 AuthModule 가져와야 합니다.

FormsModuleONLY를 사용하는 AuthModule경우 FormModuleIN을 기본값으로 가져올 필요가 없습니다.AppModule

그래서 다음과 같이 AuthModule:

import { NgModule }      from '@angular/core';
import { FormsModule } from '@angular/forms';

import { authRouting } from './auth.routing';
import { LoginComponent, SignupComponent } from './auth.component';

@NgModule({
  imports:      [ 
    authRouting,
    FormsModule
   ],
  declarations: [ 
    SignupComponent,
    LoginComponent
  ]
})
export class AuthModule { }

그런 다음 다른 곳에서 AppModule사용하지 않으면 가져 오기를 잊어 버리십시오 FormsModule.


이 오류를 제거하려면 다음 두 단계를 따라야합니다.

  1. 앱 모듈에서 FormsModule 가져 오기
  2. @NgModule 데코레이터에서 가져 오기 값으로 전달

기본적으로 app.module.ts는 다음과 같아야합니다.

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule }   from '@angular/forms';       
    import { AppComponent }  from './app.component';
    import {AppChildComponent} from './appchild.component';
    @NgModule({
      imports:      [ BrowserModule,FormsModule ],
      declarations: [ AppComponent, AppChildComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

도움이되기를 바랍니다.


Simple Soultion : app.module.ts에서

예 1

import {FormsModule} from "@angular/forms";  
// add in imports 

imports: [
 BrowserModule,
 FormsModule
 ],

예 2

[(ngModel)]을 사용하려면 app.module.ts에서 FormsModule을 가져와야합니다.

import { FormsModule  } from "@angular/forms";     
@NgModule({
  declarations: [
    AppComponent, videoComponent, tagDirective, 
  ],
  imports: [
    BrowserModule,  FormsModule

  ],
  providers: [ApiServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

당신은 수입에 필요한 FormsModule 당신의 루트 이 구성 요소는 루트 즉 인 경우 모듈 app.module.ts

app.module.ts를 엽니 다.

@ angular / forms 에서 FormsModule 가져 오기

전의:

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

@NgModule({
imports: [
   FormsModule
],
})

앱 모듈에서 FormsModule가져옵니다 .

응용 프로그램이 잘 실행될 수 있습니다.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {ContactListCopmponent} from './contacts/contact-list.component';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

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

[(ngModel)]먼저 사용해야하는 경우 가져 오기 FormsModule를 수행 app.module.ts한 다음 가져 오기 목록을 추가 해야합니다 . 이 같은:

app.module.ts

  1. 수입 import {FormsModule} from "@angular/forms";
  2. 수입품 추가 imports: [ BrowserModule, FormsModule ],

app.component.ts

  1. 예: <input type="text" [(ngModel)]="name" >
  2. 그리고 <h1>your name is: {{name}} </h1>

Angular 5를 사용하고 있습니다.

제 경우에는 RactiveFormsModule도 가져와야했습니다.

app.module.ts (또는 anymodule.module.ts)

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

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],

Angular 7을 사용하고 있습니다.

FormBuilder 클래스를 사용하여 리 액티브 양식을 생성하기 때문에 RactiveFormsModule을 가져와야합니다.

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

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

허용 된 솔루션을 적용한 후에도 누군가 여전히 오류가 발생하는 경우 입력 태그에서 ngModel 속성을 사용하려는 구성 요소에 대해 별도의 모듈 파일이 있기 때문일 수 있습니다. 이 경우 허용 된 솔루션을 구성 요소의 module.ts 파일에도 적용합니다.


이 질문은 Angular 2에 관한 것이지만 Angular 4에 있으며 이러한 답변 중 어느 것도 도움이되지 않았습니다.

Angular 4에서 구문은 다음과 같아야합니다.

[(ngModel)]

도움이 되었기를 바랍니다.


FormsModule을 올바르게 가져온 후에도 여전히 오류가 발생하면 프로젝트가 컴파일되지 않고 (무엇 일 수있는 다른 오류로 인해) 솔루션이 브라우저에 반영되지 않았기 때문에 터미널 또는 (Windows 콘솔)을 확인하십시오!

제 경우에는 콘솔에 다음과 같은 관련없는 오류가 있습니다. 'ApiService'유형에 'retrieveGithubUser'속성이 없습니다.


모듈에서 ngModel 을 사용하려면 FormsModule 을 가져와야 합니다.

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

@NgModule({
  imports: [
    FormsModule,
  ],

})
export class AbcModule { }

ngModelFormsModule 에서 온 것입니다. 이러한 종류의 오류가 발생할 수있는 경우가 있습니다.

  1. 구성 요소가 선언 된 모듈, ngModel이 사용되는 구성 요소의 가져 오기 배열로 FormsModule을 가져 오지 않았습니다.
  2. FormsModule을 다른 모듈에서 상속 된 하나의 모듈로 가져 왔습니다. 이 경우 두 가지 옵션이 있습니다.
    • FormsModule을 모듈 : module1 및 module2 모두에서 가져 오기 배열로 가져 오도록하십시오. 규칙 : 모듈 가져 오기는 가져온 모듈에 대한 액세스를 제공하지 않습니다 (가져 오기는 상속되지 않음).

enter image description here

  • FormsModule을 module1의 가져 오기 및 내보내기 배열로 선언하여 model2에서도 볼 수 있습니다.

enter image description here

  1. (In some version I faced this problem) You have imported correctly the FormsModule but the problem is on the input HTML tag. You must add the name tag attribute for input and the object bound name in [(ngModel)] must be the same as the name into the name attribute

    enter image description here


In ngModule you need to import FormsModule, because ngModel is coming from FormsModule. Please modify your app.module.ts like the below code I have shared

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

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

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

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

For my scenario, I had to import both [CommonModule] and [FormsModule] to my module

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

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }

You need to import the FormsModule

Open app.module.ts

and add line

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

and

@NgModule({
imports: [
   FormsModule
],
})

This is for the folks who use plain JavaScript instead of Type Script. In addition to referencing the forms script file on top of the page like below

<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>

you should also tell the the module loader to load the ng.forms.FormsModule. After making the changes my imports property of NgModule method looked like below

imports: [ng.platformBrowser.BrowserModule, ng.forms.FormsModule],

Happy coding!


Sometimes you get this error when you try to use a component from a module, which is not shared, in a different module.

For example, you have 2 modules with module1.componentA.component.ts and module2.componentC.component.ts and you try to use the selector from module1.componentA.component.ts in a template inside module2 (e.g. <module1-componentA [someInputVariableInModule1]="variableFromHTTPRequestInModule2">), it will throw the error that the someInputVariableInModule1 is not available inside module1.componentA.component.ts - even though you have the @Input() someInputVariableInModule1 in the module1.componentA.

If this happens, you want to share the module1.componentA to be accessible in other modules. So if you share the module1.componentA inside a sharedModule, the module1.componentA will be usable inside other modules (outside from module1), and every module importing the sharedModule will be able to access the selector in their templates injecting the @Input() declared variable.


I upgraded from RC1 to RC5 and received this error.

I completed my migration (introducing a new app.module.ts file, changing package.json to include new versions and missing modules, and finally changing my main.ts to boot accordingly, based on the Angular2 quick start example).

I did an npm update and then an npm outdated to confirm the versions installed were correct, still no luck.

I ended up completely wiping the node_modules folder and reinstalling with npm install - Voila! Problem solved.


When I first did the tutorial, main.ts looked slightly different from what it is now. It looks very similar, but note the differences (the top one is correct).

Correct:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Old tutorial code:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);

Sometimes if we are already imported BrowserModule, FormsModule and other related Modules but I get the same Error then I realized that we need import them in Order, in my case I missed it. So order should be like BrowserModule, FormsModule, ReactiveFormsModule.

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

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

Hope this helps someone .. :)


For any version from Angular 2, you need to import FormsModule in your app.module.ts file and it will fix the issue.


Recently I found that mistake happens not only in case when you forgot import FormsModule in your module. In my case problem was in this code

<input type="text" class="form-control" id="firstName"
                   formControlName="firstName" placeholder="Enter First Name" 
                   value={{user.firstName}} [(ngModel)]="user.firstName">

I fix it with change formControlName -> name

<input type="text" class="form-control" id="firstName"
                   name="firstName" placeholder="Enter First Name" 
                   value={{user.firstName}} [(ngModel)]="user.firstName">

I hope this answer save time for somebody who have the same problem.

참고URL : https://stackoverflow.com/questions/38892771/cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-input

반응형