Angular 2 - get a reference to the formGroup - forms

In Angular 2 template driven forms, I can write
<form #form="ngForm">
[...]
</form>
ngForm is a FormGroup, as fare as I could understand. How do I grab that object in the corresponding component?
class FormComponent {
formGroup: FormGroup; // How do I have the form INJECTED AUTOMATICALLY by the framework? Something like a ViewChild, but it's not a view
}
It must be simple but the documentation only shows how to use the form in the template.
Thanks
EDIT: the type of what I want to grab is NgForm, not FormGroup!

You can access any template variable from the component using ViewChild decorator. In you case:
class FormComponent {
#ViewChild('form') formGroup;
ngOnInit() {
this.formGroup.statusChanges().subscribe(() => {
// Your code here!
});
console.log(this.formGroup); // Inspect the object for other available property and methods.
}
}

Related

Detect a click outside of an element

There is some components in Ionic that do not provide an event that is emitted when focus is lost.
For example ion-input provides ionBlur. On the other hand there is other elements like ion-content where I need to detect an outside click, but without knowing which event to use.
Is there a way to achieve that without being limited to the proposed events in the documentation?
I found this article that shows a way to use a custom directive to detect an outside click:
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '#angular/core';
#Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef : ElementRef) {
}
#Output()
public clickOutside = new EventEmitter();
#HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(null);
}
}
}
The directive can then be used this way, after declaring it in the concerned module:
<!-- HTML Template -->
<ion-content (clickOutside)="handleOutsideClick()"><!-- ... --></ion-content>
<!-- Typescript code -->
handleOutsideClick() {
//Handle My outside Click
}
Yeah, It's been 7 months since asked.
Stucked with the same issue; this solved the issue
TS
#ViewChild('content') content: ElementRef
#HostListener('document:click', ['$event'])
andClickEvent(event) {
if (!this.content.nativeElement.contains(event.target)) {
if (!this.navCtrl.isTransitioning() && this.navCtrl.getActive()) {
this.close()
}
}
}
HTML
<ion-content #content>

Wrapping a FormControl in Angular (2+)

I'm trying to create a custom form control in Angular (v5). The custom control is essentially a wrapper around an Angular Material component, but with some extra stuff going on.
I've read various tutorials on implementing ControlValueAccessor, but I can't find anything that accounts for writing a component to wrap an existing component.
Ideally, I want a custom component that displays the Angular Material component (with some extra bindings and stuff going on), but to be able to pass in validation from the parent form (e.g. required) and have the Angular Material components handle that.
Example:
Outer component, containing a form and using custom component
<form [formGroup]="myForm">
<div formArrayName="things">
<div *ngFor="let thing of things; let i = index;">
<app-my-custom-control [formControlName]="i"></app-my-custom-control>
</div>
</div>
</form>
Custom component template
Essentially my custom form component just wraps an Angular Material drop-down with autocomplete. I could do this without creating a custom component, but it seems to make sense to do it this way as all the code for handling filtering etc. can live within that component class, rather than being in the container class (which doesn't need to care about the implementation of this).
<mat-form-field>
<input matInput placeholder="Thing" aria-label="Thing" [matAutocomplete]="thingInput">
<mat-autocomplete #thingInput="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
So, on the input changing, that value should be used as the form value.
Things I've tried
I've tried a few ways of doing this, all with their own pitfalls:
Simple event binding
Bind to keyup and blur events on the input, and then notify the parent of the change (i.e. call the function that Angular passes into registerOnChange as part of implementing ControlValueAccessor).
That sort of works, but on selecting a value from the dropdown it seems the change events don't fire and you end up in an inconsistent state.
It also doesn't account for validation (e.g. if it's "required", when a value isn;t set the form control will correctly be invalid, but the Angular Material component won't show as such).
Nested form
This is a bit closer. I've created a new form within the custom component class, which has a single control. In the component template, I pass in that form control to the Angular Material component. In the class, I subscribe to valueChanges of that and then propagate the changes back to the parent (via the function passed into registerOnChange).
This sort of works, but feels messy and like there should be a better way.
It also means that any validation applied to my custom form control (by the container component) is ignored, as I've created a new "inner form" that lacks the original validation.
Don't use ControlValueAccessor at all, and instead just pass in the form
As the title says... I tried not doing this the "proper" way, and instead added a binding to the parent form. I then create a form control within the custom component as part of that parent form.
This works for handling value updates, and to an extent validation (but it has to be created as part of the component, not the parent form), but this just feels wrong.
Summary
What's the proper way of handling this? It feels like I'm just stumbling through different anti-patterns, but I can't find anything in the docs to suggest that this is even supported.
Edit:
I've added a helper for doing just this an angular utilities library I've started: s-ng-utils. Using that you can extend WrappedFormControlSuperclass and write:
#Component({
selector: 'my-wrapper',
template: '<input [formControl]="formControl">',
providers: [provideValueAccessor(MyWrapper)],
})
export class MyWrapper extends WrappedFormControlSuperclass<string> {
// ...
}
See some more documentation here.
One solution is to get the #ViewChild() corresponding to the inner form components ControlValueAccessor, and delegating to it in your own component. For example:
#Component({
selector: 'my-wrapper',
template: '<input ngDefaultControl>',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NumberInputComponent),
multi: true,
},
],
})
export class MyWrapper implements ControlValueAccessor {
#ViewChild(DefaultValueAccessor) private valueAccessor: DefaultValueAccessor;
writeValue(obj: any) {
this.valueAccessor.writeValue(obj);
}
registerOnChange(fn: any) {
this.valueAccessor.registerOnChange(fn);
}
registerOnTouched(fn: any) {
this.valueAccessor.registerOnTouched(fn);
}
setDisabledState(isDisabled: boolean) {
this.valueAccessor.setDisabledState(isDisabled);
}
}
The ngDefaultControl in the template above is to manually trigger angular to attach its normal DefaultValueAccessor to the input. This happens automatically if you use <input ngModel>, but we don't want the ngModel here, just the value accessor. You'll need to change DefaultValueAccessor above to whatever the value accessor is for the material dropdown - I'm not familiar with Material myself.
I'm a bit late to the party but here is what I did with wrapping a component which might accept formControlName, formControl, or ngModel
#Component({
selector: 'app-input',
template: '<input [formControl]="control">',
styleUrls: ['./app-input.component.scss']
})
export class AppInputComponent implements OnInit, ControlValueAccessor {
constructor(#Optional() #Self() public ngControl: NgControl) {
if (this.ngControl != null) {
// Setting the value accessor directly (instead of using the providers) to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
}
control: FormControl;
// These are just to make Angular happy. Not needed since the control is passed to the child input
writeValue(obj: any): void { }
registerOnChange(fn: (_: any) => void): void { }
registerOnTouched(fn: any): void { }
ngOnInit() {
if (this.ngControl instanceof FormControlName) {
const formGroupDirective = this.ngControl.formDirective as FormGroupDirective;
if (formGroupDirective) {
this.control = formGroupDirective.form.controls[this.ngControl.name] as FormControl;
}
} else if (this.ngControl instanceof FormControlDirective) {
this.control = this.ngControl.control;
} else if (this.ngControl instanceof NgModel) {
this.control = this.ngControl.control;
this.control.valueChanges.subscribe(x => this.ngControl.viewToModelUpdate(this.control.value));
} else if (!this.ngControl) {
this.control = new FormControl();
}
}
}
Obviously, don't forget to unsubscribe from this.control.valueChanges
I have actually been wrapping my head around this for a while and I figured out a good solution that is very similar (or the same) as Eric's.
The thing he forgot to account for, is that you can't use the #ViewChild valueAccessor until the view has actually loaded (See #ViewChild docs)
Here is the solution: (I am giving you my example which is wrapping a core angular select directive with NgModel, since you are using a custom formControl, you will need to target that formControl's valueAccessor class)
#Component({
selector: 'my-country-select',
templateUrl: './country-select.component.html',
styleUrls: ['./country-select.component.scss'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: CountrySelectComponent,
multi: true
}]
})
export class CountrySelectComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnChanges {
#ViewChild(SelectControlValueAccessor) private valueAccessor: SelectControlValueAccessor;
private country: number;
private formControlChanged: any;
private formControlTouched: any;
public ngAfterViewInit(): void {
this.valueAccessor.registerOnChange(this.formControlChanged);
this.valueAccessor.registerOnTouched(this.formControlTouched);
}
public registerOnChange(fn: any): void {
this.formControlChanged = fn;
}
public registerOnTouched(fn: any): void {
this.formControlTouched = fn;
}
public writeValue(newCountryId: number): void {
this.country = newCountryId;
}
public setDisabledState(isDisabled: boolean): void {
this.valueAccessor.setDisabledState(isDisabled);
}
}
NgForm is providing an easy way to manage your forms without injecting any data in a HTML form. Input data must be injected at the component level not in a classic html tag.
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)>...</form>
Other way is to create a form component where all the data model is binded using ngModel ;)

ng-valid and ng-invalid classes in angular dart forms are no more exposed

Dart: 1.24.2;
Angular: 4.0.0;
I created some CSS rules based on .ng-valid and .ng-invalid classes in angular forms. But, in last releases, it seems that ng-valid and ng-invalid classes are no more exposed, so my CSS rules are no more working.
Is it correct?
if yes, how can I by-pass this change?
Edit1: Test case
I simply generated a brand new project with angular and angular-material in my IDE (WebStorm). It generates a simple todo application. I took the todo_list_component.html and wrapped the whole content with a <form> </form> tag. In the todo_list_component.dart I have added an import for angular_forms and added formDirectives to the directives list.
Inspecting the form in dartium no ng-valid class has been added. The only class added, in my case is: class="_ngcontent-umj-2"
Edit2: Shortcut
Not very elegant, but working:
<form #form="ngForm" [class.ng-valid]="form.valid" [class.ng-invalid]="!form.valid">
Yes, this behavior changed in a recent release of angular_forms.
Previously, the NgControlStatus directive was included in list of formDirectives. However, this caused every component that used forms to pay the price for these host bindings.
Now, if you want the behavior, you need to include NgControlStatus explicitly in the directives list of the #Component.
https://github.com/dart-lang/angular/blob/master/angular_forms/lib/src/directives/ng_control_status.dart#L15
I don't know whether they are exposed or not.
At first I would recommend you to work with "Model driven forms" - and set the validation in your component. In my opinion it is better for UnitTests and easier to handle.
and here an example:
Specify CSS (test.component.css) class:
.error {
border: 2px solid red;
}
Component (test.component.ts):
imports ...;
#Component({
selector: 'test-component',
templateUrl: 'test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
form: FormGroup;
constructor(private navCtrl: NavController, private auth: AuthService, private toast: ToastController, private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
email: ['', [
Validators.required,
Validators.email]],
password: ['', [
Validators.required,
Validators.minLength(6)]],
});
}
and your template (test.component.html) looks like this:
<form [formGroup]="form" (ngSubmit)="login()" [ngClass]="{'error': !form.valid}">
*** YOUR FORM DIV'S HERE ***
</form>
I don't know if this is working with Dart too. But as Verena commented, we can help you most if you upload some code.

Angular 2 FormControl.reset() doesn't work, but .resetForm() does (but typescript error)

In my Angular 2 form, I have the following typescript:
export class UserEditComponent implements OnChanges {
#Input() userModel: IUserModel;
#Output() onSave: EventEmitter<IUserModel> = new EventEmitter<IUserModel>();
#ViewChild("userEditForm") userEditForm: FormControl;
private userNameIsValid = true;
constructor(private httpService: HttpService) {
}
ngOnChanges (changes: SimpleChanges) {
this.userEditForm.resetForm();
console.log(this.userEditForm);
}
....
}
and template html:
<form class="form-horizontal" #userEditForm="ngForm" (ngSubmit)="onSaveUser()" novalidate>
....
</form>
I tried using the .reset() function, but it did nothing. The .resetForm actually resets the _submitted property of the form from true back to false, however, it gives me a TypeScript error Property resetForm does not exist on type FormControl.
First, is resetForm an actual function that works? I can't seem to find any documentation for it... but it works and .reset() doesn't.
Second, how can I get rid of this TypeScript error? Do I need to update my typings for Angular 2?
Declare userEditForm as NgFormlike this:
#ViewChild("userEditForm") userEditForm: NgForm;
Now you can access .resetForm() method.
You should import NgForm from #angular/forms and try this.
OnClear(userEditForm: NgForm) {
userEditForm.reset();
}
Add import:
import { NgForm } from "#angular/forms";
ngOnChanges (changes: SimpleChanges) {
/** add this **/
form.reset();
console.log(this.userEditForm);
}

React - Redux, submit a form with data from child components

I have a component which is a form, with a number of child components. What is the best way to consolidate the data from all of the child components, when submitting the form? Below is one idea, is this the correct method? I pass a reference to a function that will update a property of a form upon change in a component. What is best practice? Thanks.
import React from 'react';
import { Component , PropTypes} from 'react';
import { connect } from 'react-redux';
import { saveData } from '../actions/index'
import {bindActionCreators} from 'redux';
export default class MyClass extends Component {
constructor(props) {
super (props);
this.formData = {};
this.setFormData = this.setFormData.bind(this);
this.onSubmitHandler = this.onSubmitHandler.bind(this);
}
setFormData(key, value){
this.formData[key] = value;
}
onSubmitHandler(evt){
this.props.saveData(this.formData);
}
render (){
return (
<div>
<form onSubmit = {this.onSubmitHandler} >
<div >
<NameComponent setFormData = {this.setFormData}/>
<AddressComponent setFormData = {this.setFormData}/>
//...lots more components
</form>
</div>
);
}
}
export default connect( mapStateToProps, {saveData)(MyClass)
Yes, this approach is correct, because children are generally expected to delegate to parent that is responsible for them. In fact, that's how Redux Form works. <Field /> input components delegate their state to a Higher Order <Form /> wrapper.
The problem with your approach is that you have to do a lot of repetitive stuff on your own (such as calling onChange, delegating the value etc).
We use Redux Form for one of our projects and it's great as it integrates forms, react and redux. I find myself writing much less code and there is build in validation for both remote, local submission, submission from child components and other neat stuff.
My suggestion is to go with Redux Form instead of reinventing the wheel.