使指令@Input 成为必需 [英] Make directive @Input required

查看:29
本文介绍了使指令@Input 成为必需的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 AngularJs 中,我们可以将指令属性设为必需.我们如何使用@Input 在 Angular 中做到这一点?文档没有提到它.

In AngularJs we could make a directive attribute required. How do we do that in Angular with @Input? The docs don't mention it.

例如

@Component({
  selector: 'my-dir',
  template: '<div></div>'
})
export class MyComponent {
  @Input() a: number; // Make this a required attribute. Throw an exception if it doesn't exist.
  @Input() b: number;
}

推荐答案

检查ngOnInit()(在执行构造函数时尚未设置输入)属性是否有值.

Check in ngOnInit() (inputs aren't yet set when the constructor is executed) whether the attribute has a value.

Component({
    selector: 'my-dir',
    template: '<div></div>'
})
export class MyComponent implements OnInit, OnChanges {
    @Input() a:number; // Make this a required attribute. Throw an exception if it doesnt exist
    @Input() b:number;

    constructor(){
    }

    ngOnInit() {
       this.checkRequiredFields(this.a);
    }

    ngOnChanges(changes) {
       this.checkRequiredFields(this.a);
    }

    checkRequiredFields(input) {
       if(input === null) {
          throw new Error("Attribute 'a' is required");
       }
    }
}

如果值未设置为 null,您也可以检查 ngOnChanges(changes) {...}.另请参阅 https://angular.io/docs/ts/latest/api/core/OnChanges-interface.html

You might also check in ngOnChanges(changes) {...} if the values wasn't set to null. See also https://angular.io/docs/ts/latest/api/core/OnChanges-interface.html

这篇关于使指令@Input 成为必需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆