Reputation: 11
I would like to submit a form automatically when all the fields in the form are valid,.
How can I trigger a form submission with codes but no buttons?
Here is an example form:
<form [formGroup]="dummyForm">
<label>
<input type="text" formControlName="dummyText" ng-change="autoSubmit()"/>
</label>
</form>
component.ts:
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { RxFormBuilder, RxwebValidators } from '@rxweb/reactive-form-validators';
@Component({
selector: 'dummy-page',
templateUrl: './dummy.component.html',
styleUrls: ['./dummy.component.sass']
})
export class DummyComponent {
dummyForm: FormGroup;
constructor(
private readonly _formBuilder: RxFormBuilder
) {
// Do something here
}
ngOnInit(): void {
this.dummyForm = this._formBuilder.group({
dummyText: ['', [
RxwebValidators.pattern({
pattern: {
validPattern: /^1234$/
}
})
]]
});
}
autoSubmit(): void {
if (!this.dummyForm.valid) {
return;
} else {
// Trigger form submission here, how?
}
}
}
Upvotes: 1
Views: 3851
Reputation: 1846
You can subscribe on form valueChanges
this.dummyForm.valueChanges.subscribe({
next: data => {
if (this.dummyForm.valid) {
// send data
}
},
});
Upvotes: 0
Reputation: 41
You can subscribe to statusChanges observable of your FormGroup like this:
this.dummyForm.statusChanges.subscribe(status => {
if (status === 'VALID') {
// form submission here
}
});
Upvotes: 2