-2

Following is the example code , for what i am doing.

Model Component

//app.models.ts
export class Employee{
 Name:string;
 Salary:number;
}

Root Component

//app.component.ts 
import { Component } from '@angular/core';   
import { Employee } from './app.models.ts';

@Component({
  selector: 'my-app',
  template: '<input type="text" [(ngModel)]="emp.Name"><hello [employee]="emp"></hello>'
})
export class AppComponent  {
  emp:Employee;
  constructor(){
    this.emp=new Employee();
    this.emp.Name="Neeraj";
  }      
}

Child Component

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Employee } from './app.models.ts';
@Component({
  selector: 'hello',
  template: `<h1>{{displayName}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})

export class HelloComponent implements OnChanges  {
  @Input() employee: Employee;
  displayName:string;
  ngOnChanges(changes: SimpleChanges) {
        console.log('Life cycle hook method called.');
        this.displayName='Hello, '+this.employee.Name;
        }
}

Textbox text changes are not being detecting in the child component.

Live Demo

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Neeraj Singh
  • 151
  • 2
  • 6

2 Answers2

0

You can watch the inputs changes with ngOnChanges (https://angular.io/api/core/OnChanges)

class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

EDIT Your value emp is not modified when the property name is changed, so no changes are detected in the child component. What you can do is pass only the property

@Component({
  selector: 'my-app',
  template: '<input type="text" [(ngModel)]="emp.Name"><hello [name]="emp.Name"></hello>'  
})
export class AppComponent  {
  emp:Employee;
  constructor(){
    this.emp=new Employee();
    this.emp.Name="Neeraj";
  }

}

And

@Component({
  selector: 'hello',
  template: `<h1>{{displayName}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})

export class HelloComponent implements OnChanges  {
  @Input() name: String;
  displayName:string;
  ngOnChanges(changes: SimpleChanges) {
        console.log('Life cycle hook method called.');
        this.displayName='Hello, '+this.name;
        }
}
HMarteau
  • 654
  • 4
  • 18
0

There are two ways you can choose either

  • using ngOnChanges
  • using getter and setter from typescript

Read out more here

Working example

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215