Make directive @Input required

前端 未结 8 483
無奈伤痛
無奈伤痛 2021-01-30 06:26

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({
  selec         


        
8条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 07:09

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

    Component({
        selector: 'my-dir',
        template: '
    ' }) 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

提交回复
热议问题