Muhammad Saleh
Muhammad Saleh

Reputation: 359

How to set input's default value from another input's value in Angular?

In Angular 2+ I have a component which accepts two inputs

totalCarsNumber is mandatory however availableCarsNumber is not

What I'm looking for is how to set the default value for availableCarsNumber to be exactly as totalCarsNumber

I tried this but it didn't work:

@Input() totalCarsNumber: Number;
@Input() availableCarsNumber = this.totalCarsNumber;

Upvotes: 2

Views: 5176

Answers (2)

Abinesh Joyel
Abinesh Joyel

Reputation: 2093

Using property setter in input property we can detect and set default value to it

  availableCars:number = null;
  @Input() availableCarsNumber: number = null;

  //This property setter is called anytime the input property changes
  @Input() set totalCarsNumber(val: number){
    if(this.availableCarsNumber === null){
     this.availableCarsNumber = val;
    }
    this.availableCars = val;
  }

  //This getter is called when reading and displaying data
  get totalCarsNumber(){
    return this.availableCars;
  }

I made a small demo of it you can check it stackblitz

Upvotes: 3

Maciej Caputa
Maciej Caputa

Reputation: 1891

;TDLR Values passed to through Angular's @Input become available after the component is initialised, hence, the value of totalCarsNumber is available in ngOnInit. Hence, you have to use ngOnInit to implement it.

An optional input needs to be annotated with question suffix. The number type should be lowercased. Moreover, we set null as a default value for the optional input so that we can check it later if it has been set.

@Input() totalCarsNumber: number;
@Input() availableCarsNumber?: number = null;

Then we can use ngOnInitto check if the value for this.availableCarsNumber has been provided on a component otherwise it will be null and then we set the value to totalCarsNumber.

ngOnInit() {
  this.availableCarsNumber = this.availableCarsNumber === null ? this.totalCarsNumber : this.availableCarsNumber;
}

Upvotes: -1

Related Questions