Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation for dynamically generated reference Template Driven Angular

I am creating a dynamic form, I am going through my own way through template driven, I don't want to create with the reactive approach. Everything is working fine but only validations are creating a problem for me. I have uploaded a small piece of code of my project

  <ng-container *ngFor="let a of UserFormArray; let i = index">
   <form #f="ngForm" name="FormName">
    <ng-container *ngFor="let ab of a; let i2 = index">
      <ng-container *ngIf="ab.type === 'text'">
        <input type={{ab.type}} pInputText name={{ab.name}} ngModel 
                                     #{{ab.name}}="ngModel" required>
           <ng-container *ngIf="ab.name.errors?.required">
                    <div>
                        Input Error
                    </div>
           </ng-container>
      </ng-container>
    </ng-container>
  </form>
 <p-button label="Click" (onClick)="sender(f)"></p-button>
</ng-container>

The problem is that I am not able to put validation here, I am using the template-driven approach and I don't want to go for reactive form so please don't suggest the reactive link, it's my requirement to go with template driven, I know I am missing the small thing. But not able to figure it out

like image 312
Dexter's Web Lab Avatar asked May 01 '26 07:05

Dexter's Web Lab


1 Answers

You can create template reference variable dynamically but you should know that this variable is unique within embedded view.

So propably you're looking for the following:

<input ... #ngModel="ngModel" required>
    <ng-container *ngIf="ngModel.errors?.required">

Ng-run Example

like image 55
yurzui Avatar answered May 02 '26 22:05

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!