javascriptangularangular-input

Angular Input() takes undefined after providing default value


Below is Input decorator used with 3 variables and assigned default values to each variable

  @Input() score: number = 0;
  @Input() text: string = 'test';
  @Input() color: string = 'red';

This is how I am passing values to the component inside a ngFor.

  [text]="item.name"
  [score]="item.score"
  [color]="item.color"

If my item object does not contain color property then the color variable in the component should take 'red' as default value.

But when I log it as :

ngOnInit() {
    console.log(this.score, this.text, this.color);
  }

then the color variable takes undefined as value.

Here is the console for above logs for

8 "English" undefined
6 "Spanish" "blue"

The 1st log is when the item does not contain color property, and 2nd is when it contains property color with value blue


Solution

  • You can use a setter to the input property to determine whether it is a valid value or not and assign it to a default value as

    private color: string;
    
    @Input('color')
    set Color(color: string) {
        this.color = color || 'red';
    }
    

    A sample created at https://stackblitz.com/edit/angular-setter-for-null-input-property