Detect Changes in a Form in Angular using Observables

Posted By : Avilash Choudhary | 21-Dec-2017

Hi Guys, Today I have got interesting topic of observables. How observables help us in angular. In Angular or Angular 2 or 4 promises have been replaced with observables, through which we can subscribe on changes in asynchronous tasks. 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. This can be done with the help of observables, you just have to subscribe to the form instance , you will be notified whenever anything change in the form.

 

There are many ways of form creation in Angular, using FormBuilder, in this case you are creating form programmatically . or another way is to just create html with form element.

 

 

<form novalidate="" updatectatemplateform="ngForm">
<div class="ctaRuleTemplate">
<div class="col-md-3">
<div class="form-group"><label i18n="">Name</label> <input class="form-control" name="ctaTemplateName" type="text" /></div>

<div class="form-group"><label i18n="">Payroll Type</label> <ng-select moduleid="==" name="payrollType" placeholder="Payroll Type" readonly="readonly"></ng-select></div>
</div>

<div class="col-md-3">
<div class="form-group"><label i18n="">Category</label> <ng-select name="category" placeholder="Category"></ng-select></div>

<div class="form-group"><label i18n="">Select Calculation Unit</label> <ng-select name="calculationUnit" placeholder="Select Calculation Unit"></ng-select></div>
</div>
</div>
</form>

 

In your html template. you have to declare form instance with # and assigned ngForm into it.

 

In your component ts file

 

 

 @ViewChild('updateCtaTemplateForm') updateCtaTemplateForm;    // view child on form instance
	 this.updateCtaTemplateForm.control.valueChanges
            .debounceTime(500)
            .subscribe(values => // save data to the server );

We have included debounceTime of 500 ms, this observable will broadcast data after 500 ms when user stops writing into the input field. This is useful, it won’t broadcast the data, when user writing into any field, when user stops it wait for 500ms then broadcast the data. Forms are very powerful in Angular.

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..