9

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?

1

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

5 Comments

I know all of this, the answer is not related with this.
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?
How to get always a type number in the input decorator?
Ok, sorry I didn't underestand what you really mean. Now I underestand everything
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.