Make directive @Input required

2020-05-13 09:48发布

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

Eg.

@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;
}

7条回答
啃猪蹄的小仙女
2楼-- · 2020-05-13 10:28

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");
       }
    }
}

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

查看更多
登录 后发表回答