Having trouble retrieving the parent object in Angular OnInit method?

I am facing an issue with attaching a custom validator to an Angular Form Control. The Form Controls are initialized in the ngOnInit method, and I want the validator to check if a field has input only when a boolean class member this.shouldCheck is true.

The problem arises when trying to access this class member from the validator function as it cannot find the instance of this. Despite TypeScript supposedly solving scoping issues with this, I am unable to figure out how to check the boolean in the validator.

This is a snippet of my component.ts:

// The value of shouldCheck is tied to a checkbox on the form
private shouldCheck: boolean = false;

constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
        this.employeeCreateForm = this.formBuilder.group({
            firstName: [null, [
                this.myRequiredValidator,
                Validators.maxLength(30),
                Validators.pattern('[^<|]+$')]],
            lastName: [null, [
                this.myRequiredValidator,
                Validators.maxLength(40),
                Validators.pattern('[^<|]+$')]]
        }

And here is my custom validator:

myRequiredValidator(control: AbstractControl): ValidationErrors | null {
        // Perform basic "required field" validation if shouldCheck is true
        if (this.shouldCheck) {
            return !!control.value ? null : {required: true};
        }
        // Do not apply validation error otherwise
        return null;
    }

Regardless of where I initialize shouldCheck, the validator function struggles to resolve this and therefore fails to instantiate the FormGroup.

I even attempted using a simple null check:

if (this && this.shouldCheck) {
    // Validate fields
}

However, this workaround allows the FormGroup construction but still encounters difficulties resolving this, even after initialization. While I understand ngOnInit runs after the constructor, I have exhausted all possibilities and would appreciate any help.

Thank you.

Answer №1

  nameIsRequiredValidator = (control: AbstractControl): ValidationErrors | null => {
    // check if validation is required and apply "required field" validation
    if (this.validationRequired) {
      return !!control.value ? null : {required: true};
    }
    // no validation error needed
    return null;
  } 

Alternatively

  ngOnInit() {
    this.employeeForm = this.formBuilder.group({
      firstName: [null, [
        this.myCustomValidator(),
        Validators.maxLength(30),
        Validators.pattern('[^<|]+$')]],
      lastName: [null, [
        this.myCustomValidator(),
        Validators.maxLength(40),
        Validators.pattern('[^<|]+$')]]
    }

    myCustomValidator(): (AbstractControl) => ValidationErrors | null {
      return (control: AbstractControl): ValidationErrors | null => {
        // check if validation is required and apply "required field" validation
        if (this.validationRequired) {
          return !!control.value ? null : {required: true};
        }
        // no validation error needed
        return null;
      };
    }

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

Customized IntelliSense naming for overloaded parameters with conditional tuple types

In TypeScript 3.1, I have a generic function with arguments of either (TInput, string) or (string), depending on whether the generic's type parameter TInput extends undefined. To achieve this, I'm utilizing the new generic rest parameters feature ...

Building a NestJS/Prisma RESTful API to retrieve data from a related field

I am diving into creating my very own Rest API using Nestjs and Prisma for the first time. This project is a basic representation of an inventory management system, keeping things simple with shelves and boxes to store items. The structure in place has tab ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

The overall package size post transitioning to standalone versions and incorporating lazy loading

Initially, my app had a setup where each component had its own module and lazy-loading was implemented. This resulted in a main.js bundle size of 2mb. However, after converting to standalone components with lazy loading, the bundle size increased to 4mb. ...

Tips for successfully transferring a JsonifyObject<T> from Remix's useLoaderData<typeof loader> to a function

Encountering a TypeScript error while trying to import JsonifyObject in the Remix 2.9.2 route code below... Argument of type 'JsonifyObject<IdAndDate>' is not assignable to parameter of type 'IdAndDate'. Struggling to figure ou ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...

"Introducing a brand new column in ng2-smart-table that is generated from an Object

Can anyone provide guidance on how to create a new column from an Object datatype? I'm struggling with this task. Below are the settings and data for better clarity: private settings = { columns: { firstName: { title: &apo ...

Developing a Progressive Web App with ASP.NET Core 3 and Angular is a powerful

I have embarked on the journey of building an Angular SPA in ASP.NET Core 3. To kick things off, I created a new project, utilized the Angular template, and upgraded all packages to version 8.2.9 of Angular. Setting up a seamless CI/CD pipeline to Azure wa ...

Troubleshooting issue with image dimensions in Angular within CKEditor content

One issue I am facing is with CKEditor, where images inserted into Rich Text Fields have their height and width attributes set in a CSS style tag. For example: <img alt="" src="https://something.cloudfront.net/something.jpg" style="height:402px; ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

The 'setState' property is not found on the 'Window' type

I am encountering an issue with the code snippet in my index.tsx file let state = {}; window.setState = (changes: any) => { state = Object.assign({}, state, changes); ReactDOM.render(<App {...state} />, document.getElementById("root")); ...

Developing web applications with Angular 6, C#, and MVC involves dynamically generating and returning JsonResults from the controller in the form of

I have been working on exporting datasets to Excel within an Angular 6 application. To achieve this, I have been utilizing XLSX and File-save functionalities as outlined in the following example: https://medium.com/@madhavmahesh/exporting-an-excel-file-in- ...

Using React components within an Angular 6 application: A comprehensive guide

Looking for advice on how to reuse React components in an Angular 6 application. Can anyone recommend the best approach for accomplishing this? ...

Issue during deployment: The type 'MiniCssExtractPlugin' cannot be assigned to the parameter type 'Plugin'

I'm working on deploying a Typescript / React project and have completed the necessary steps so far: Created a deployment branch Installed gh-pages for running the deployed application Added a deploy command as a script in the package.j ...

Exploring the integration of namespace with enums in TypeScript

In the angular project I am currently working on, we are utilizing typescript for development. One key aspect of our project is an enum that defines various statuses: export enum Status { ACTIVE = 'ACTIVE', DEACTIVE = 'DEACTIVE' } ...

Difficulty with setting up a basic Angular 5 environment

I am facing difficulties in setting up and running Angular5 on my system. Here are the steps I followed in my home directory: $ sudo npm install @angular/cli -g $ ng new my-verbsandvocab $ cd my-verbsandvocab $ ng serve However, I encountered an erro ...

Generating TypeScript declarations for legacy CommonJS dependencies with the correct "module" setting

One of my challenges involves creating type declarations for outdated dependencies that produce CJS modules and lack typings. An example is the aabb-3d module (although this issue isn't specific to that particular module). To generate the declaration ...