1

I'm building an Angular application and i'm using jquery to change an input class dynamically using focusin and focusout events, as you can see in the code below:

$(".form-input").focusin(function(){
        $(this).addClass("focus");
        $(this).prev().addClass("label-focus");
});
$(".form-input").focusout(function(){
        $(this).removeClass("focus");
        $(this).prev().removeClass("label-focus");
});

My doubt is: I read in the angular docs that i should'nt use angular with jquery and that i should use databinding instead, but how can i do it?

  • 1
    The problem here is that you're using a CSS selector to attach events. There isn't an equivalent feature in Angular, because Angular uses template expressions or host bindings. For example; we don't know if the above code is run for **all** `.form-input` elements on the HTML page across multiple components. This is why it's difficult to port jQuery to Angular. jQuery is selector based. Angular is component based. I think it's better to throw away all your jQuery code and just do it the proper Angular way. – Reactgular Jun 06 '18 at 13:07

4 Answers4

2

Pardeep's answer works, but you can do this using pure CSS. Add this to your component style:

.form-input:focus {
    background-color: red;
}
p4r1
  • 2,490
  • 16
  • 18
  • good answer, but the original code is mutating the DOM element next to `.form-input` by adding/removing `.label-focus` when the input has focus or not. I don't think you can do this via pure CSS. – Reactgular Jun 06 '18 at 13:09
  • The answer is partially right because by focusing the input, you can't dynamically change the correspondig label with pure CSS. Or did I miss something? – Alex Maiburg Jun 06 '18 at 13:11
1

You could also use ngClass:

<label for="input" [ngClass]="{ 'active': isActive}">Name</label>
<input
  type="text"
  name="input"
  [ngClass]="{ 'active': isActive}"
  (focus)="isActive = !isActive"
  (blur)="isActive = !isActive">

And declare a property in the component:

export class AppComponent  {
  isActive = false;
}

https://stackblitz.com/edit/toggle-class-on-focus-and-blur-event-in-angular

Alex Maiburg
  • 690
  • 5
  • 10
0

Try to avoid jQuery with angular as official stated instead simply use databinding or even binding in Angular.

for example -

<input (focus)='focusEvent($event)'>

More about events read out here -

Or

You can add CSS classes conditionally using ngClass too.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Since you want to use a class, I would recommend using the document.

Start by declaring the document as part of your component :

export class MyComponent {
  document = document;
}

(I know, seems useless, but it's required).

Once you did that, you can use template variables and activeElement like this

<label [class.input-focused]="document.activeElement === nameInput">Name :</label>
<input #nameInput [class.focused]="document.activeElement === nameInput">