Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 check if one of the form controls is in focus

In Angular2 app, I have a form ("FormGroup").

The form has a few forms on it.

this.mainForm = this.fb.group({
       firstPart:this.firstForm,
       secondPart:this.secondForm,
       thirdPart:this.thirdForm
       ....
});

My requirment is, in some place in my code I need to check if a form (not the main form, but some of the inner forms) is in focus.

Actually I need something like this.:

isFormInFocus(formName) {
   let innerForm = this.mainForm.controls[formName];
   //NOT EXIST - I need something like this...
   return innerForm.focus;
}

My issue is I don't find how to check this even to a specific form control.

if I will know this, I can, as a workaround, loop all form controls in the inner form and check if one of them is in focus...

Any Ideas?

like image 395
Batsheva Avatar asked Dec 03 '17 12:12

Batsheva


People also ask

How does Angular detect focus?

document. hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.

How do you check if a FormControl is required?

validator({} as AbstractControl); This will return an Object with the list of validators that are present on your FormControl . You can then check for the required key in the Object. If it exists and its value is true then you can be sure that a Required Validator is applied on the FormControl .

What is pristine in form control?

"pristine" means the user hasn't changed the value since it was displayed in this form. So given a user has an autocomplete input that looks up airports nearby, when the user selects an option then we set the value of the FormControl to the selected option.

How does Angular determine change in form control?

In Angular we have observables which subscribe to form value changes. what you have to do is, subscribe to the form instance and detect any changes to the form. Suppose you don't want to include save button on your form. whenever user change any thing in the form save data to the server.


1 Answers

I had a similar need. I didn't see any valid properties off the form control either. I then pulled in a ViewChild reference with an Input or ElementRef to get the actual <input> in my case. Again I found no property for focus that I could use.

So, unfortunately I was left keeping track of the focus state myself (which seems crazy). It works well, just seems like overkill.

HTML

<input md-no-float placeholder="City or Zip" type="text" matInput formControlName="destination" (focus)="autocompleteFocus()" (blur)="autocompleteBlur()">

TS

isDestinationFocused: boolean;

autocompleteFocus() {
    this.isDestinationFocused = true;
}

autocompleteBlur() {    
    this.isDestinationFocused = false;
}
like image 181
BRass Avatar answered Oct 27 '22 14:10

BRass