That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.