@Input的严格类型检查

时间:2019-03-06 06:28:47

标签: javascript angular typescript

我已经创建了a sample demo

如您所见,我正在将ipNumber = '99';传递给HelloComponent

但是@Input就像

@Input() someVal : number;

我想在@Input中传递字符串时引发错误。

正确的输入应该是

ipNumber = 99;

不是

ipNumber = '99';

3 个答案:

答案 0 :(得分:1)

您可以使用ngOnChanges Lifecycle hook验证输入

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

查看本文以获取更多信息:https://medium.com/@abdelelmedny/angular-input-decorators-5d38089070aa

答案 1 :(得分:0)

如果将其放在constructor内,则由于角度组件的生命周期尚未达到此点而无法使用,因此可以将其放入ngOnInit或在函数中调用,然后在ngOnInit或之后发生的任何其他生命周期中调用它。 请检查以下代码:

ngOnInit() {
     if(typeof this.someVal !== 'number') {
      console.error("This is not a number");
    }
  }

答案 2 :(得分:0)

检查@Input类型的最简单方法是使用javascript提供的 typeof 。如果值是数字,它将检查数据类型,然后我们将抛出以下错误

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

相关问题