programing tip

ngModel을 사용하는 Angular 2 양방향 바인딩이 작동하지 않습니다.

itbloger 2020. 9. 16. 07:24
반응형

ngModel을 사용하는 Angular 2 양방향 바인딩이 작동하지 않습니다.


'input'요소의 알려진 속성이 아니고 해당 속성과 일치하는 지시문이 없으므로 'ngModel'에 바인딩 할 수 없습니다.

참고 : im using alpha.31

import { Component, View, bootstrap } from 'angular2/angular2'

@Component({
    selector: 'data-bind'
})
@View({
    template:`
        <input id="name" type="text" 
            [ng-model]="name" 
            (ng-model)="name = $event" />
        {{ name }}
    ` 
})
class DataBinding { 
    name: string;

    constructor(){
        this.name = 'Jose';
    }
}

bootstrap(DataBinding);

Angular는 9 월 15 일에 최종 버전을 출시했습니다. Angular 1과 달리 Angular ngModel2에서는 양방향 데이터 바인딩을 위해 지시문을 사용할 수 있지만 [(ngModel)]( Banana in a box syntax ) 와 같이 약간 다른 방식으로 작성해야 합니다 . 거의 모든 angular2 코어 지시문은 kebab-case이제 지원하지 않습니다 camelCase. 대신 .

이제 ngModel지시어에 속한 FormsModule사용자들은, 왜해야 에서 내부 모듈 의 메타 데이터 옵션 (NgModule). 그 후 페이지에서 지시문 을 사용할 수 있습니다 .importFormsModule@angular/formsimportsAppModulengModel

app / app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1>
    <input type="text" [(ngModel)]="myModel"/>
    {{myModel}}
  `
})
export class AppComponent { 
  myModel: any;
}

app / app.module.ts

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

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

export class AppModule { }

app / main.ts

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

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

데모 Plunkr


키 포인트:

  1. angular2의 ngModel은 FormsModule이 AppModule의 일부로 사용 가능한 경우에만 유효합니다.

  2. ng-model 구문 적으로 잘못되었습니다.

  3. 대괄호 [..]는 속성 바인딩을 나타냅니다.
  4. 원 중괄호 (..)는 이벤트 바인딩을 나타냅니다.
  5. [(..)]는 일반적으로 바나나 상자라고하는 양방향 바인딩을 의미하므로 사각형 및 원형 중괄호를 함께 사용할 때.

따라서 오류를 수정하십시오.

1 단계 : FormsModule 가져 오기

import {FormsModule} from '@angular/forms'

2 단계 : 추가하여 AppModule의 배열을 다음과 같이 가져옵니다.

imports :[ ... , FormsModule ]

Step 3: Change ng-model as ngModel with banana boxes as

 <input id="name" type="text" [(ngModel)]="name" />

Note: Also, you can handle the two way databinding separately as well as below

<input id="name" type="text" [ngModel]="name" (ngModelChange)="valueChange($event)"/>

valueChange(value){

}

As per Angular2 final, you do not even have to import FORM_DIRECTIVES as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.

Just replace ng-model with ngModel and wrap it in a box of bananas. But you have spilt the code into two files now:

app.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'ng-app',
  template: `
    <input id="name" type="text" [(ngModel)]="name"  />
    {{ name }}
  `
})
export class DataBindingComponent {
  name: string;

  constructor() {
    this.name = 'Jose';
  }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above

@NgModule({
  declarations: [DataBindingComponent],
  imports:      [BrowserModule, FormsModule],
  bootstrap:    [DataBindingComponent]
})
export default class MyAppModule {}

platformBrowserDynamic().bootstrapModule(MyAppModule);

In the app.module.ts

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

Later in the @NgModule decorator's import:

@NgModule({
imports: [
BrowserModule,
FormsModule
]

})

Angular 2 Beta

This answer is for those who use Javascript for angularJS v.2.0 Beta.

To use ngModel in your view you should tell the angular's compiler that you are using a directive called ngModel.

How?

To use ngModel there are two libraries in angular2 Beta, and they are ng.common.FORM_DIRECTIVES and ng.common.NgModel.

Actually ng.common.FORM_DIRECTIVES is nothing but group of directives which are useful when you are creating a form. It includes NgModel directive also.

app.myApp = ng.core.Component({
    selector: 'my-app',
    templateUrl: 'App/Pages/myApp.html',
    directives: [ng.common.NgModel] // specify all your directives here
}).Class({
    constructor: function () {
        this.myVar = {};
        this.myVar.text = "Testing";
    },

});

The answer that helped me: The directive [(ngModel)]= not working anymore in rc5

To sum it up: input fields now require property name in the form.


instead of ng-model you can use this code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input #box (keyup)="0">
    <p>{{box.value}}</p>`,
})
export class AppComponent  {}

inside your app.component.ts


Add below code to following files.

app.component.ts

<input type="text" [(ngModel)]="fname" >
{{fname}}
export class appcomponent {
fname:any;
}

app.module.ts

import {FormsModule} from '@angular/forms';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent],
bootstrap:    [ AppComponent ]
})

Hope this helps

참고URL : https://stackoverflow.com/questions/31623879/angular-2-two-way-binding-using-ngmodel-is-not-working

반응형