1

If i have a custom component <my-component></my-component> can I make it so that it always has a custom attribute? For example, <my-component data-custom-attr></my-component>

B Roy Dawson
  • 611
  • 1
  • 6
  • 18

1 Answers1

0

You can do it by using an @Input and in the ngOnInit trigger an error if the value is null

Component({
    selector: 'my-component',
    template: '<div></div>'
})
export class MyComponent {
    @Input() data-custom-attr:number; // Make this a required attribute. Throw an exception if it doesnt exist
    @Input() data-custom-attr-2:number;

    constructor(){

    }

    ngOnInit() {
      if(null == data-custom-attr) throw new Error("Attribute 'data-custom-attr' is required");
    }
}

src solution

Abel Valdez
  • 2,368
  • 1
  • 16
  • 33