Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected].

https://i.stack.imgur.com/4oZ6w.png

takenEmailAddress(control: FormControl): Promise<any> | Observable<any> {
  const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      if (control.value === '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2450415750645d0a47">[email protected]</a>') {
        resolve({'emailIsTaken': true});
      } else {
        resolve(null);
      }
    }, 1500);
  });

  return promise;
}

The advantages of observables in terms of development and readability are significant. Is there a way to convert something like this into an observable pattern?

An Observable pattern that will update the errors object of the emailAddress formControl with emailIsTaken: true when the user types [email protected]

https://i.stack.imgur.com/Es5J7.png

Furthermore, what is the equivalent of resolve and reject in the observable pattern?

Answer №1

In the FormControl class, there are members named ValueChanges and StatusChanges that return Observables which can be directly applied to a FormControl instance.

An example implementation could look something like this:

email: FormControl;
emailTaken: bool;

ngOnInit() {

    this.email.valueChanges.subscribe(value => {
        if (value === '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72061701060b320b5c11">[email protected]</a>")
            this.emailTaken = true;
        else
            this.emailTaken = false;
        },
        error => //Handle error here
    );
}

This method may not be optimal, but it serves as a starting point for understanding. Whenever the value in the FormControl changes, its validity is checked.

It's important to note that this example does not support asynchronous operations.

Furthermore, you can create an observable directly from a promise:

const observable = Observable.fromPromise(takenEmailAddress(control));
observable.subscribe(value => /*Do something to handle the value*/ ,
                     err => /*Handle the error*/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate the mat-select selectionChange trigger when making changes to the form via patchValue

I have been working with an angular reactive form that includes a mat-select element with a selectionChange event. After updating the form using patchValue, I noticed that the selectionChange event does not trigger. I'm unsure how to proceed and woul ...

Error occurred due to changed expression after validation

I am facing an issue in my Angular app while implementing checkboxes with ngModel. When I try to implement it, I encounter the following error message. Can someone please help me resolve this problem? Error core.js:5873 ERROR Error: ExpressionChangedAfter ...

Display only the clear button within the p-calendar element

I am struggling to make a Clear button appear only on the p-calendar component. myComponent.html <p-calendar value="#{property.propDate}" id="date" [showIcon]="true" [utc]='true' placeholder="{{ timePickerPlaceHolder }}" [showTrans ...

Error encountered in lodash.js in Angular 2 framework

I have been attempting to implement lodash for a datatable. Here are the steps I followed: First, I tried running npm install lodash, but encountered an error stating that the package could not be found After researching the issue, I attempted npm in ...

Angular - Sharing data between components with response value

I am currently in the process of restructuring my project, focusing on establishing communication between unrelated components while also waiting for a return value from a function call. Imagine having component1 with function1() and component2 with funct ...

Tips for correctly referencing the router link within the mat-sidenav component in Angular 7

As a newcomer to Angular, I am facing an issue where I need to use the same router link in both my mat-list-item and the sub mat-sidenav-content. For instance: [routerLink]="['/list',{outlets: {sidebar: ['general', employee.userId]}}] ...

Having trouble transitioning to Angular2 RC? Let's chat at [email protected] - we can help!

I encountered an error while attempting to upgrade angular2 to RC. Due to JWT dependencies on RC, I had to switch to @angular. M:\workspace\Angular2StartKit>npm install npm ERR! addLocal Could not install M:\workspace\Angular2StartK ...

The expected function is being executed, yet none of the inner functions are invoked

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One particular unit test involves opening a modal, changing values in a form, and saving them. Everything goes smoothly until it reaches the promise inside the open() ...

Each property of an object has its own unique key, yet they all share the same data type

I have a single-use object with only three properties, all of which should be of the same type. The code below currently achieves this, but I'm curious if there is a more efficient way to declare the type for timingsObject: let timingsObject: ...

Tips for creating TypeScript Google Cloud Functions using webpack

I'm currently facing a challenge while coding a Google Cloud Function using TypeScript. The concept involves having handler functions defined for various Cloud Functions in separate files within the source repository, along with some code that is shar ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

Is there a way to retrieve all potential string literals from an Array<>?

Can something similar be achieved in TypeScript? const options: Array<'Option1' | 'Option2' | 'Option3'> = []; // specify all available options: 'Option1' | 'Option2' | 'Option3' as show ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

Having an issue where the Material Angular 6 DatePicker is consistently displaying my selected date as one day earlier

I've encountered a strange issue with the current version of the Material Angular DatePicker. After upgrading from A5 to A6, it started to parse my date one day earlier than expected. You can see an example of this problem here: https://stackblitz.com ...

Tips for transferring data from an Angular @Input property to another variable and displaying it in a child component

I am dealing with the following parent HTML structure: <p>Parent</p> <app-child [mainData]="mainData"></app-child> In parent.ts, I have the following code: mainData = []; ngOnInit() { this.myService((res)=>{ this.mainData = ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

Issue with Material UI DateTimePicker not submitting default form value

Currently, I am utilizing React for my frontend and Ruby on Rails for my backend. My issue lies in submitting the value from my materialUI DateTimePicker via a form. The problem arises when I attempt to submit the form with the default DateTime value (whic ...

Changing the color of a Chart.js chart in Angular: A step-by-step guide

I've been struggling to change the color of my chart without success. Any assistance on this matter would be greatly appreciated. Despite trying to assign color values to datasets, I am still unable to achieve the desired result. This is a snippet f ...