Home > database >  How to control developer property input to components via ESLint?
How to control developer property input to components via ESLint?

Time:10-23

I'm building a design system, which can be imported into anyone's Angular library.

I wish to be able to, assuming they have this custom ESLint Plugin installed, throw error or warning messages when a developer is using the design system (made up of pre-built Angular components) and passes in (or doesn't pass anything in) invalid data into the component.

For example, lets say I create a button component.

This button component has an Input for the style - I.E Primary, Secondary, Tertiary. Each style modifies the look and feel of the button.

If however, someone was to pass in 'MadeUpStyle' into it - how would I create an ESLint Plugin to specifically throw up an error or a warning to advise them that what they're doing is not recommended?

Furthermore, if they do not pass anything into this Input, that an error would be presented stating that this is a required Input.

Whilst my research has helped me discover pages such as this, I can't seem to find anything online that specifically shows examples of someone using a plugin to validate component inputs.

Any help or point in the right direction would be appreciated.

CodePudding user response:

What I understood is You are looking to achieve two things:

  • Type Safety for input properties of the components
  • Required input properties

For, type safe input property, you can leverage Typescript itself, In tsConfig file you need to enable strict type checking for templates. Refer this for more details on it: https://angular.io/guide/template-typecheck

For required inputs you can create a custom decorators like this:

function Required(target: object, propertyKey: string) {
  Object.defineProperty(target, propertyKey, {
    get() {
      throw new Error(`Attribute ${propertyKey} is required`);
    },
    set(value) {
      Object.defineProperty(target, propertyKey, {
        value,
        writable: true,
        configurable: true,
      });
    },
  });
} 

and then in your component:

    Component({
      selector: 'test-app',
      template: '<div></div>',
    });
    export class TestComponent {
      @Input() @Required a: number; // Usage of required
    }
  • Related