I have 2 components
- Customer Component
- Preview Component
Customer class
export class Customer {
public firstname:string;
public lastname:string;
public designation:string;
public company:string;
}
customer.component.html
<div class="row">
<div class="col-md-6">
<input type="text" [(ngModel)]='customer.firstname' placeholder="First Name">
</div>
<div class="col-md-6">
<input type="text" [(ngModel)]='customer.lastname' placeholder="Last Name">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" [(ngModel)]='customer.designation' placeholder="Designation">
</div>
<div class="col-md-6">
<input type="text" [(ngModel)]='customer.company' placeholder="Company">
</div>
</div>
<div class="row">
<div class="col-md-12">
<iGlobal-preview [customer]='customer'></iGlobal-preview>
</div>
</div>
customer.component.ts
import { Component, OnInit } from '@angular/core';
import { Customer } from 'app/models/customer';
@Component({
selector: 'iGlobal-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.scss']
})
export class CustomerComponent implements OnInit {
customer:Customer;
constructor() {
this.customer = new Customer();
}
ngOnInit() {
}
click(){
console.log("customer",this.customer)
}
}
preview.component.html
<div class="row">
<textarea name="preview" [(ngModel)]='previewtext' rows="10" style="width: 100%"></textarea>
</div>
preview.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Customer } from 'app/models/customer';
@Component({
selector: 'iGlobal-preview',
templateUrl: './preview.component.html',
styleUrls: ['./preview.component.scss']
})
export class PreviewComponent implements OnInit {
@Input("customer")
customer:Customer
previewtext:string="";
constructor() { }
ngOnInit() {
this.previewtext = "Customer Name : "+this.customer.firstname+" "+this.customer.lastname
}
}
My requirement is to show the preview of whatever is entered in customer component, pass the object to preview component and perform some action later on on preview component.
How to do this change detection correctly so that i can get any changes made on parent component on to child component?
ngOnChanges(changes: SimpleChanges) { if (changes.customer.currentvalue) { this.customer = changes.customer.currentValue; }this lifecyclehook ngOnChanges updates the input any time it changes from the outside. If it helped I will provide an answer - sagat