Here is the proper solution to this. (ANGULAR 2 to 9)
Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.
Example:
I have an object interface named bike:
export interface bike {
isBike?: boolean;
wheels?: number;
engine?: string;
engineType?: string;
}
You made a component named app-bike where you need to pass the properties of bike with @input decorator of angular. But you want that isBike and Wheels properties must have a default value (ie.. isBike: true, wheels: 2)
export class BikeComponent implements OnInit {
private _defaultBike: bike = {
// default isBike is true
isBike: true,
// default wheels will be 2
wheels: 2
};
@Input() newBike: bike = {};
constructor() {}
ngOnInit(): void {
// this will concate both the objects and the object declared later (ie.. ...this.newBike )
// will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
this.newBike = { ...this._defaultBike, ...this.newBike };
// console.log(this.newBike);
}
}
For more detailed article refer to this.
Refer Destructuring assignment from here