Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Custom Validation for dynamically generated textboxes in Angular

The code for dynamically generated textboxes uisng *ngFor

<tr *ngFor="let computer in _Computers; let i = index;">
<td>{{computer.Name}}</td><td>{{computer.Optional}}</td>
<td> <input matInput [formControl] = "frmCtrl"  name="UnitofPrice" [(ngModel)]="computer[i]">
</td>
<td>{{computer.UnitofPrice}}</td>

Typescript code

public frmCtrl: FormControl = new FormControl('', this.customValidator());
customValidator() {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if ((!control.value)) {
        return { 'textRequired': true };
      }
      return null;
    };
 }

The above code works fine. That is whenever the textbox is empty, it is showing error. Suppose, I want to validate only the textboxes based on the "Optional" property of the computer list. Here, How to pass the computer Id or optional property to custom validator function? Please suggest.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I would utilize a form and formarray, besides, what you have now, is one single formcontrol for your whole array, so I cannot see how it works for your array.

Also, the validator you have written is basically a required validator, so you could use the inbuilt validator for that. So I suggest the following:

I have hardcoded _Computers array, I build the form, I loop the _Computers and add formcontrols to the formarray. Based on the Optional property I set Validators.required for the unit price only for those that the Optional value is false. Here I am pushing 2 formcontrols to each formgroup in the array, the name and the unitOfPrice, you can push any amount you want.

I make a getter for the formarray, just for easier access. All in all, code would look like this:

_Computers = [
  { Name: 'name1', Optional: true, UnitOfPrice: null },
  { Name: 'name2', Optional: false, UnitOfPrice: null },
];
myForm!: FormGroup;

constructor(private fb: FormBuilder) {
  this.myForm = this.fb.group({
    computers: this.fb.array([]),
  });
  this._Computers.forEach((x: any) => {
    if (x.Optional) {
      this.computersArr.push(this.fb.group({
        name: [x.Name],
        unitOfPrice: [null]
      }));
    } else {
      this.computersArr.push(this.fb.group({
        name: [x.Name],
        unitOfPrice: [null, [Validators.required]]
      }));
    }
  });
}

get computersArr() {
  return (this.myForm.get('computers') as FormArray).controls;
}

I have been lazy and used any here, please type your data instead!

The template would then show the form, and we can display a message of required if it has such a validator:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div formArrayName="computers">
    <div *ngFor="let computer of computersArr; let i = index">
      <div [formGroupName]="i">
        <label>{{computer.get('name').value}}</label>
        <input formControlName="unitOfPrice" />
        <small *ngIf="computer.get('unitOfPrice').hasError('required')">Required!!</small>
      </div>
    </div>
  </div>
</form>

Above is using div's but you can easily replicate the same for a table.

Here is a STACKBLITZ for your reference.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!