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

146
Vistas
Creating a reusable method attach to input field for multiple components in Angular

I am beginner in angular and started working on angular 12 project. I am working on reactive forms where I am adding on Blur method to add class to my input field on some error conditions to give some styling to input fields.

I am able to do that but now I have 12-15 components with forms. I want to utilize the same functionality on all the components. Is there a way I can do this without repeating the code in ts file for onblur method. Below is my code.

 <form [formGroup]="changePasswordForm" (ngSubmit)="submitForm()">
                    <div class="form-group" [ngClass]="f.oldPassword.invalid && ((f.oldPassword.dirty || f.oldPassword.touched))?'has-error':''">
                        <label>Old Password<span class="error-red">*</span></label>
                        <input type="password" class="form-control input-type2" formControlName="oldPassword" (blur)="onBlur($event)">
                        <div class="error error-msg">
                            <div *ngIf="f.oldPassword.errors?.required">
                                <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Old password is required.
                            </div>
                        </div>
                    </div>
</form>

Component.ts

  onBlur(e: any) {
    if (e.target.className && e.target.className.indexOf('ng-invalid') > 0) {
      e.target.className = e.target.className.replace('has-success', '');
    } else {
      e.target.className = e.target.className + ' has-success';
    }
  }

I am writing the same piece of code in all the form components to get my work done. I know one way to deal above is create service and write it down over there. But I did some research and found that we can create directives for such things. But I am not sure how to do it. Any help will be appreciated. Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a directive on the input

@Directive({ selector: "[errorStyling]" })
export class ErrorStylingDirective {

  constructor(
    private elem:ElementRef
  ) { }

  @HostListener("blur")
  onBlur() {
    // do something here
  }

}

You could also use @HostBinding('class.xxx') approach to set the updated classes

about 4 years ago · Juan Pablo Isaza 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