Make directive @Input required

前端 未结 8 612
無奈伤痛
無奈伤痛 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条回答
  •  萌比男神i
    2021-01-30 06:51

    For me, I had to do it this way:

    ngOnInit() {
        if(!this.hasOwnProperty('a') throw new Error("Attribute 'a' is required");
    }
    

    FYI, If you want to require @Output directives, then try this:

    export class MyComponent {
        @Output() myEvent = new EventEmitter(); // This a required event
    
        ngOnInit() {
          if(this.myEvent.observers.length === 0) throw new Error("Event 'myEvent' is required");
        }
    }
    

提交回复
热议问题