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?
document. hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.
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 .
"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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With