Efficient Data Binding
An effective approach is to utilize TypeScript setters and getters to ensure that changes in fullName are synchronized with both firstName and lastName:
get lastName() {
return this._lastName;
}
set lastName(lastName:string) {
this._lastName = lastName;
this.fullName = this._firstName + ' ' + this._lastName;
}
get firstName() {
return this._firstName;
}
set firstName(firstName:string) {
this._firstName = firstName;
this.fullName = this._firstName + ' ' + this._lastName;
}
By implementing this method, any updates made to lastName or firstName will automatically reflect in fullName:
var p = new Person();
p.lastName = 'last';
p.firstName = 'first';
console.log(p.fullName); // will display 'first last'
Alternative Solution
Angular2's default behavior does not support direct property changes within objects. It only detects modifications at references. However, you can customize this by leveraging the ngDoCheck hook method.
You can use the KeyValueDiffers class (to be injected) within ngDoCheck to track alterations in specific objects.
Refer to the following link for detailed information:
Here is an example implementation:
@Component({
selector: 'my-component',
(...)
})
export class MyComponent implements DoCheck {
@Input() person: Person;
differ: any;
constructor(differs: KeyValueDiffers) {
this.differ = differs.find([]).create(null);
}
ngDoCheck() {
var changes = this.differ.diff(this.person);
if (changes) {
changes.forEachChangedItem((elt) => {
if (elt.key === 'firstName' || elt.key === 'lastName' ) {
this.person.fullName = this.person.firstName + ' ' + this.person.lastName;
}
});
}
}
}
When there is an update in the prop1
property, the doSomethingIfProp1Change
function is triggered.
Check out a demonstration on Plunkr: http://plnkr.co/edit/uvOKMXQa9Ik8EiIhb60Y?p=preview.