Angular4 mandatory Input on component

Viewed 1363

I've a component with the following input

@Input() id: string

I would like this input to be mandatory, which means that if I call my component without specifying it, it would throw a js error.

I can do it in the ngOnInit, but I imagine there is a keyword for this ?

2 Answers

You can throw error in ngOnInit method after checking input property:

ngOnInit() {
    if (!id) {
      throw new Error('No ID provided!');
    }
  }

The possible solution is:-

    @Input() id: string;

    ngOnInit(){

// 'id' will be 'undefined' so provide a default data when component loads individually, so possible solution below

    if(!id){     
    this.id = '.......';
    /*---------Other Implementation-------------*/
    }

    }
Related