Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda