Search code examples
angularangular-directive

ngModel error issue in Angular. input property binding issue


I am trying to bind a property using ngModel but it is giving error again and again. I have convert method defined in component which takes one parameter. I am not able to understand why it is giving issue. html file code

<input type="text" [(ngModel)]="my_message" />
<button (onclick)="convert({'message':my_message})">Submit</button>

Component class code

import { Component, OnInit } from '@angular/core';
import { UppercaseConvertorService } from '../../services/uppercase-convertor.service';
import { HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-uppercase-convertor',
  templateUrl: './uppercase-convertor.component.html',
  styleUrls: ['./uppercase-convertor.component.css']
})
export class UppercaseConvertorComponent implements OnInit {
  public result: any;
  constructor(private _service: UppercaseConvertorService) { }

  ngOnInit() {
  }
  public convert(obj): any {
    this._service.convertToUpperCase(obj).subscribe(
      res => this.result = res,
      (err: HttpErrorResponse) => {
        console.error(err);

      }
    )
  }
}

Error: enter image description here


Solution

  • You have to define my_message in component like below. The error says its not defined in the component. ngModel actually binds your component data variables to your html input UI controls

    public result: any;
    public my_message;
    

    then in convert put it like this

    public convert(): any {
      const obj = {'message': this.my_message}
        this._service.convertToUpperCase(obj).subscribe(
    

    and in the html file change it to

    <button (onclick)="convert()">Submit</button>