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

A peculiar quirk with Nuxt.js radio buttons: they appear clickable but are somehow not disabled

I’m having an issue with a radio button that won’t check. It seems to be working fine on other pages, but for some reason it just won't click here. <div class="form-group"> <label class="control-label&q ...

The issue with Rxjs forkJoin not being triggered within an Angular Route Guard

I developed a user permission service that retrieves permissions from the server for a specific user. Additionally, I constructed a route guard that utilizes this service to validate whether the user possesses all the permissions specified in the route. To ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Angular 2 and .NET Core 2.0 triggering an endless loop upon page refresh detection

My application, built with dotnet core 2.0 and angular 2, allows me to view member details. The process begins with a list page displaying all the members from a SQL Server database. Each member on the list has a link that leads to an individual details pa ...

How to pass parameters between pages in Ionic 2 using navParams when the return nav button is clicked

Is there anyone familiar with how to return a simple value (or JSON) by clicking on the return button in Ionic 2's navigation bar? I understand that navParam can be used to send a value when pushing a page, but I am unsure how to implement the same fu ...

"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click. The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

Guide on integrating a personalized theme into your Ionic 5 app

I'm looking to customize the theme of my Ionic 5 app by adding a red-theme to variables.scss @media (prefers-color-scheme: red) { :root { --ion-color-primary: red; Afterwards, I attempted to initialize it in index.html <meta name=" ...

Can we guarantee that the key and its corresponding value are both identical strings in Typescript?

Is it possible to enforce the key of a Record to be the same as the inner name value in a large dataset? interface Person<T> { name: T title: string description: string } type People = Record<string, Person<string>> // example dat ...

What could be causing my code to fail in retrieving lists from the SharePoint site?

I've been attempting to retrieve lists from a SharePoint site using the provided code, however, the list isn't appearing in the response. Could someone please offer assistance with this issue? I have tried various other solutions, but the problem ...

Ways to display map results in multiple columns utilizing react

I am facing a challenge and seeking guidance on how to achieve a specific layout using React. My goal is to display results in two columns as shown below: item 1 | item 4 item 2 | item 5 item 3 | item 6 I have attempted to check the array length and dete ...

Issue arises when attempting to use the useEffect hook in React with Typescript to reset states upon the component unmounting

I'm facing an issue with my useEffect cleanup when the component unmounts and setting states simultaneously. My code involves selecting a client by clicking on them and setting their ID to send in an API request: const setClient = () => { setC ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

Issue with the integration of Angular and Java Jersey API arises when attempting to encode utf-8 whitespaces at the end, resulting in invalid JSON

I'm facing an issue with Angular while making an HTTP GET request. It throws a "Http failure during parsing" error because the JSON response contains whitespace characters at the end. I find it puzzling why the server is returning them. Is there a wa ...

Creating two number-like types in TypeScript that are incompatible with each other can be achieved by defining two

I've been grappling with the challenge of establishing two number-like/integer types in TypeScript that are mutually incompatible. For instance, consider the following code snippet where height and weight are both represented as number-like types. Ho ...

Ways to verify the validity of a string as a DATE, TIME, or DATETIME

Is there a way to validate a date input in a MySQL DATE field without actually updating the field? Can this validation be done from PHP? Is it possible to query the MySQL server to check if a DATE, TIME, or DATETIME input is considered valid? Alternative ...

Switching up the icons of Angular/PWA in Ionic 5 - here's how!

Is there a way to change the default icons from @angular/pwa using "ionic cordova resources" command? I have tried this but the icons still remain unchanged. Any suggestions on how to achieve this? ...

Issue encountered while attempting to utilize the useRef function on a webpage

Is it possible to use the useRef() and componentDidMount() in combination to automatically focus on an input field when a page loads? Below is the code snippet for the page: import React, { Component, useState, useEffect } from "react"; import st ...