Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom Angular Compiler Errors

I am curious if there is any way I could add a custom warning in the console, similar to the warning Angular throws when you are attempting to use the "disabled" attribute on an input which is already binded to a FormControl in the .ts file. Basically, Angular advises you to modify the ‘disabled’ attribute on the FormControl itself in the .ts tile, rather than specifying the HTML attribute in the template.

In order to ensure FormControl ‘state’-manipulating code is done in the .ts file entirely, I would also like to throw a similar warning in the console whenever someone attempts to use a said ‘required’ property in the HTML template instead of adding the Validators.required validator to the FormControl directly.

What is a good way to implement such a warning?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As mentioned in other answer you can create a directive for this. You would want to adress fields that has a formcontrol or formcontrolname, here is formControlName:

@Directive({
  selector: 'input[formControlName]'
})
export class RequiredDirective {

  constructor(private el: ElementRef) { 
    if (this.el.nativeElement.required) {
      console.error("set the required attribute on the formcontrol")
    }
  }
}

DEMO: https://stackblitz.com/edit/angular-gfbvbg?file=src%2Fapp%2Frequired.directive.ts

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading