Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 699
Varun Sukheja Avatar asked Jun 12 '19 18:06

Varun Sukheja


People also ask

How to set default values if value is null in angular 12?

With Angular 12 version you can use Nullish coalescing operator ?? in templates to set default values if value is null or undefined. Here is how you can use Nullish coalescing operator ?? in template file app.component.html. So, if my_value is null or undefined it will show the message my value is null .

What is the use of input form in angular?

Form contains multiple html input elements to take input from the user. button allows the user to submit the from to backend API an d it calls click binding event. In Angular, View is html template and controller is an typescript component. Reading input text is basic concept every Angular developer need to know.

What happens if my_value is null or undefined?

So, if my_value is null or undefined it will show the message my value is null . Else it will show the value of variable my_value. We were unable to load Disqus Recommendations.

How to read input text value in typescript in angular?

For Angular versions,less than 8, viewChild is annoted with ElementRef type in component to read the input value. Finallly, read the input value using ElementRef.nativeElement.value. Controller typescript component on reading input element value on button click. This talks about how to read input text value in typescript.


1 Answers

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

like image 116
Saksham Avatar answered Nov 13 '22 10:11

Saksham