3

I have created a sample demo

As you can see, I am passing ipNumber = '99'; to HelloComponent.

but the @Input is like

@Input() someVal : number;

I want to throw error when string is passed in @Input.

The correct input should be

ipNumber = 99;

and not

ipNumber = '99';
Liam
  • 27,717
  • 28
  • 128
  • 190
Samuel
  • 1,128
  • 4
  • 14
  • 34
  • Please check this link: https://blog.rsuter.com/angular-2-typescript-property-decorator-that-converts-input-values-to-the-correct-type/ – SU7 Mar 06 '19 at 06:44
  • use typeof to check type in your ngOninit lifecycle hook of child component – TheParam Mar 06 '19 at 06:49
  • Possible duplicate of [type checking in javascript](https://stackoverflow.com/questions/4514602/type-checking-in-javascript) – Liam Mar 06 '19 at 09:02

3 Answers3

1

You can validate your input using ngOnChanges Lifecycle hook

ngOnChanges(changes: SimpleChanges) {
        const nameType = typeof changes['name'].currentValue;
        if ( nameType !== 'string' ) {
          console.warn(`You provided ${nameType} where string was expected`);
        }
      }

Check this article for more Info:https://medium.com/@abdelelmedny/angular-input-decorators-5d38089070aa

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • If the approach of throwing an error is taken, it should be done onChanges. This is important because it ensures that an error is thrown even if the input is changed after the component is first created. – Benjamin Kindle Apr 21 '19 at 01:13
0

If you put it inside of the constructor, it won't work because the life cycle of the angular component hasn't got to this point, so you can put it in the ngOnInit or in a function and call it in the ngOnInit or any other life cycle that happens after. Please check the following code:

ngOnInit() {
     if(typeof this.someVal !== 'number') {
      console.error("This is not a number");
    }
  }
SU7
  • 1,586
  • 1
  • 18
  • 26
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
0

The simplest way to check the type of @Input is using typeof provided by javascript. It will check the data type provided value is number or not then we can throw the error like below

export class HelloComponent implements OnInit {
  @Input() name: string;
  @Input() someVal : number;

  constructor(){

  }

  ngOnInit() {
    console.log(this.someVal)

    if(typeof this.someVal !== "number" ) {
      throw new Error('Please provide only number');

    }
  }


}

Here is solution on stackblitz

TheParam
  • 10,113
  • 4
  • 40
  • 51