Using Getters and Setters

  • Here two way binding happens with the help of getters and setters

app.component.html

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

Welcome {{name}}

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'GettersNSettersDemo';
  private _name : string;

  get name(){
    return this._name;
  }
  set name(name){
    this._name = name;
    if(name==="Tyson"){
      alert('Hello Tyson');
    }
  }
}

Output : When you enter ‘Tyson’ in the text box

Leave a Comment