Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
Check if NgControl is required

I've got several custom components that wrap PrimeNG components for various reasons. Some instances of my components are used in reactive forms, and the field's "requirement" is set using Validators.required validator.

PrimeNG components provide a required attribute.

How can I inspect my component's NgControl for the required validator? There is .disabled and .invalid, but .invalid could mean anything.

Here I what I'm using now, which works for dropdowns, but would be incorrect for any other type of input.

@Component({
  selector: 'my-component',
  templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, ControlValueAccessor {
  
  @Input()
  public disabled: boolean
  @Input()
  public required: boolean

  constructor(
        @Optional() @Self() public ngControl: NgControl
  ) {
        if (this.ngControl != null) {
            this.ngControl.valueAccessor = this;
        }
    }

    ngOnInit() {
        if (this.ngControl) {
            this.required = this.ngControl.invalid;
            this.disabled = this.ngControl.disabled;
        }
    }
}

I'm sure there is a better way to do this, but I don't see how.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try to check if the control has a required validator or not like the following:

  ngOnInit() {
    if (this.ngControl) {
      this.required = this.hasRequiredValidator(this.ngControl.control);
      this.disabled = this.ngControl.disabled;
    }
  }

  hasRequiredValidator(control: AbstractControl): boolean {
    if (control.validator) {
      const validator = control.validator({} as AbstractControl);
      if (validator && validator.required) {
        return true;
      }
    }
    return false;
  }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!