Angular 2 Directive for Ensuring Required Conditions

Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive:

@Directive({
  selector: '[myRequired][ngControl]',
  providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
  @Input('myRequired') required: boolean;

  validate(control: AbstractControl): { [key: string]: any } {
    return this.required && !control.value
      ? { myRequired: true }
      : null;
  }
}

Here's an example of how to use it:

<form>
  <p><label><input type="checkbox" [(ngModel)]="isNameRequired"> Is Name Required?</label></p>
  <p><label>Name: <input type="text" [myRequired]="isNameRequired" #nameControl="ngForm" ngControl="name" [(ngModel)]="name"></label></p>
  <p *ngIf="nameControl.control?.hasError('myRequired')">This field is required.</p>
</form>

While this works when toggling between checkboxes and text boxes with input, there seems to be an issue when changing the checkbox while the text box is empty. How can I update MyRequiredValidator to trigger validation when the required property changes?

Please note that I'm only looking for modifications to MyRequiredValidator, and prefer not to add logic to the App component.

Check out the Plunker here: https://plnkr.co/edit/ExBdzh6nVHrcm51rQ5Fi?p=preview

Answer №1

Here is an example of how I would approach this:

@Directive({
  selector: '[myRequired][ngControl]',
  providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
  @Input('myRequired') required: boolean;

  ngOnChanges() {
    // This function is triggered when 'required' is updated
    if (this.control) {
      this.control.updateValueAndValidity();
    }
  }

  validate(control: AbstractControl): { [key: string]: any } {
    this.control = control;
    return this.required && !control.value
      ? { myRequired: true }
      : null;
  }
}

You can check out a live demo of this code in action on Plunker: https://plnkr.co/edit/14jDdUj1rdzAaLEBaB9G?p=preview.

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

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

Transitioning a JavaScriptIonicAngular 1 application to TypescriptIonic 2Angular 2 application

I am currently in the process of transitioning an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I have extensively researched various guides on migrating between these technologies, completed the A ...

Refresh the project once logged in using angular

Thank you in advance for your response. I am facing an issue with monitoring user activity and automatically logging them out after a certain period of inactivity. I have successfully implemented this feature in my app.component.ts file, however, it only s ...

Is there a way to omit type arguments in TypeScript when they are not needed?

Here is a function I am currently working with: function progress<T>(data: JsonApiQueryData<T>): number { const { links, meta } = data.getMeta(); if (!links.next) { return 1; } const url = new URL(links.next); return parseInt(url ...

Transferring a JSON file between components within Angular 6 utilizing a service

I have been facing an issue in passing the response obtained from http.get() in the displayresults component to the articleinfo component. Initially, I used queryParams for this purpose but realized that I need to pass more complex data from my JSON which ...

Internationalization of deferred-loaded modules within the JHipster application

I created My App using JHipster, which utilizes the JhiLanguageService in the ng-jhipster library. This service relies on the JhiConfigService to configure ngx-translate without requiring manual imports and configuration of the TranslateModule in my app.mo ...

What could be causing the issue of console.log() being called multiple times in Angular when invoking a method through text interpolation?

Utilizing Text interpolation to invoke a method. home.component.html <p>{{myMethod()}}</p> home.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './h ...

Using TypeScript with Angular, you can easily include parameters to HTML tags

I have an HTML element that looks like this: eventRender(info){ console.log(info.el); } This is the output I'm seeing: https://i.stack.imgur.com/G0hmw.png Now, I want to include these attributes: tooltip="Vivamus sagittis lacus vel augue ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

What is preventing me from accessing a JavaScript object property when using a reactive statement in Svelte 3?

Recently, while working on a project with Svelte 3, I encountered this interesting piece of code: REPL: <script lang="ts"> const players = { men: { john: "high", bob: "low", }, }; // const pl ...

Making the Angular 2 Http Service Injectable

I am fetching a large object from my server using an Angular 2 service when the website loads. The structure of the data I need to fetch is as follows: { Edu: [...], Exp: [...], Links: [...], Portfolio: [...], Skills: [...] } Here&apo ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

Issues with TypeScript: outFile in tsconfig not functioning as expected

Currently, I am utilizing Atom as my primary development environment for a project involving AngularJs 2 and typescript. To support typescript, I have integrated the atom-typescript plugin into Atom. However, I noticed that Atom is generating separate .js ...

Dynamically created HTML elements have no events attached to them in Angular and jQuery

Utilizing jQuery, I am dynamically generating new elements within an Angular Form that has been constructed using a Template Driven Forms approach. Despite successfully creating the dynamic elements, they do not seem to be assigned events/callbacks due to ...

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

What is causing the Angular HTTP Post method error "Property 'post' is undefined"?

Encountering an error while using Angular's HTTP Post method: Cannot read property 'post' of undefined. I am attempting to send my first HTTP POST request, but it is not functioning as expected. export class RegisterComponent impleme ...

Perform an HTTP POST request in Angular to retrieve the response data as a JSON object

I am currently in the process of developing a simple user authentication app. After completing the backend setup with Node.js and Passport, I implemented a feature to return JSON responses based on successful or failed authentication attempts. router.pos ...

The 'Alias[]' type does not share any properties with the 'Alias' type

I encountered an issue: The error message 'Type 'Alias[]' has no properties in common with type 'Alias'' appeared. Here is my Alias setup: alias: Alias = { id: 0, domain_id: 0, source: '', dest ...