Angular 2 @Input number issue
Asked Answered
R

2

8

I have the following component:

<component value="3"></component>

And the component code is:

  private _value:number;

  get value(): number {
    return this._value;
  }

  @Input()
  set value(value: number) {
    console.log(value);
    console.log(typeof value);
    this._value = value;
  }

The log is:

3
string

But if I bind the property like:

<component [value]="variable1"></component>

In this case I get a number if variable1 is type number.

3
number

I know there's no magic with typescript but is this the right behavior? Should Angular Input decorator do the conversion?

I'm checking types in the setters, but I get errors when typescript is compiling.

I don't want to use type any in the gettes and setter.

Any elegant solution?

Rebuild answered 3/10, 2016 at 8:24 Comment(1)
See also #39817594Xerography
L
9

When binding with brackets [], the value gets bound directly on the object.

With attribute binding, the value between the quotes gets handled as string.

Maybe have a look at the docs.


working Plunker for example usage

Lymphatic answered 3/10, 2016 at 8:41 Comment(5)
I know all of this, the answer is not related with this.Rebuild
That is how Angular 2 works - it even tells you in the docs. Without brackets (property binding) you don't bind to the actual variable, but just a string interpretation. What's your question then?Lymphatic
How to get always a type number in the input decorator?Rebuild
With [value]="3"? plnkr.co/edit/WIaTS7uenWubsP4S1OZO?p=previewLymphatic
Ok, sorry I didn't underestand what you really mean. Now I underestand everythingRebuild
C
1

Number Attribute Transformer

Since Angular 16.1 you can use @Input({ transform: numberAttribute }) to automatically convert your string value to a number value.

@Input({ transform: numberAttribute }) value?: number;

Usage:

<app-number-display [value]="2"></app-number-display>
<app-number-display value="2"></app-number-display>
<app-number-display [value]="'2'"></app-number-display>

Documentation transform Input value to number

▶️ Run on Stackblitz

Closed answered 2/8 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.