Search code examples
angularangular4-forms

how to access model or view variable in angular 4 for two way data binding


I want to access value of textarea in component class through button click function triggered through button click.
HTML

<div class="container">
  <div class="row">
    <div class="col-lg-4 col-sm-12">

        <textarea class="form-control" placeholder="Add Comment">
         {{comment}}
        </textarea>
      <button (click)="addComment($event, comment)" style="margin-top: 2%" class="btn-success">Add Comment</button>
    </div>
  </div>
</div>

component:

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

@Component({
  selector: 'app-add-comments',
  templateUrl: './add-comments.component.html',
  styleUrls: ['./add-comments.component.css']
})
export class AddCommentsComponent implements OnInit {

  comment:string = "Hellooooo";


  //commentsArr: commentsArr[];

  addComment(event, comment);

  addComment(event, comment)
  {
    console.log(this.comment);


  }

  constructor() { }

  ngOnInit() {
  }

}

I want to to access comment inside comment data inside comment component.


Solution

  • there is no scope variable in Angular 2+.

    In Angular 2+ there is NgModel which helps you with two way binding.

    https://angular.io/api/forms/NgModel

    To access value of text area in your component.

    In html

    <textarea class="form-control" [(NgModel)]=comment placeholder="Add Comment">
    <input type="button" value="Add" (click)="AddComment()" />
    

    In component:

    comment:any="";
    
    AddComment(){
    
    console.log(this.comment);
    }
    

    Here comment var will always be mapped to inputs in textarea.