Issue
when i add two or more dynamic field and i enter input with cpf number the validation happens when i enter cpf in last field, its possible to validate a input field individually?
<h1>Reactive Form Table Example</h1>
<form [formGroup]="form">
<ng-container formArrayName="cpfs">
<table class="form-group">
<tr>
< th>cpf</th>
</tr>
<ng-container *ngFor="let cpf of cpfs.controls; let i = index;">
<tbody>
<tr [formGroupName]="i">
<td>
<input type="text" class="form-control" id="cpf" formControlName="cpf" maxlength="11" />
</td>
<td *ngIf="!isValidCPF('cpf')">
CPF é invalido
</td>
<td>
<button (click)="deleteRow(i)" class="btn btn-danger">
Delete
</button>
</td>
</tr>
</tbody>
</ng-container>
</table>
<button type="button" (click)="addCpf()" class="btn btn-dark mt-5">
Add new Row
</button>
<button type="submit" class="btn btn-primary mt-5"
[disabled]="form.invalid">Submit</button>
<pre>{{ form?.value | json }}</pre>
<pre>{{ cpfForm?.value | json }}</pre>
</ng-container>
</form>
here is a link to the problem, can someone help? https://stackblitz.com/edit/angular-ivy-1d8zur?file=src/app/app.component.ts
Solution
I find solution thanks to someone who helped me, i need to to validate input at index
like code below
code in .ts
isValidCPF(index: number) {
let cpfControl = this.getCpfFormByIndex(index).get('cpf');
let cpf: String = cpfControl.value;
if (cpf.length < 11) {
return false;
}
return true;
}
getCpfFormByIndex(index: number): FormGroup {
return this.cpfs.at(index) as FormGroup;
}
in html
<h1>Reactive Form Table Example</h1>
<form [formGroup]="form">
<ng-container formArrayName="cpfs">
<table class="form-group">
<tr>
<th>cpf</th>
</tr>
<ng-container *ngFor="let cpf of cpfs.controls; let i = index">
<tbody>
<tr [formGroupName]="i">
<td>
<input
type="text"
class="form-control"
id="cpf"
formControlName="cpf"
maxlength="11"
/>
</td>
<td
*ngIf="!isValidCPF(i) && getCpfFormByIndex(i).get('cpf').dirty"
style="color:#FF000F"
>
CPF is invalid!
</td>
<td
*ngIf="isValidCPF(i) && getCpfFormByIndex(i).get('cpf').dirty"
style="color:#176105"
>
CPF is valid
</td>
<td>
<button (click)="deleteRow(i)" class="btn btn-danger">
Delete
</button>
</td>
</tr>
</tbody>
</ng-container>
</table>
<button type="button" (click)="addCpf()" class="btn btn-dark mt-5">
Add new Row
</button>
<button
type="submit"
class="btn btn-primary mt-5"
[disabled]="form.invalid"
>
Submit
</button>
<pre>{{ form?.value | json }} - iSValid {{ form.status | json }}</pre>
<pre>{{ cpfForm?.value | json }} - iSValid {{ cpfForm.status | json }}</pre>
</ng-container>
</form>
here is live example, add 3 or mor input cpf field and enter some number , it
will validate only that input field that are you is typing
here is an example how to do that, thank you everbody,
stackblitz: https://stackblitz.com/edit/angular-ivy-1d8zur?file=src/app/app.component.html
Answered By - Marcelo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.