简体   繁体   English

带有ngModel的角度ngFor和窗体错误显示

[英]Angular ngFor with ngModel and form error display

I have a form where the user can insert as many inputs as they want. 我有一个表单,用户可以在其中插入任意数量的输入。 They start with 1 input. 它们以1个输入开始。 Each input has a pattern validation. 每个输入都有一个模式验证。 I show an error if the pattern is incorrect. 如果模式不正确,则会显示错误。 The user can then add a new input field with the add button. 然后,用户可以使用添加按钮添加新的输入字段。 The new input field however has the same validation as the first input field. 但是,新输入字段具有与第一个输入字段相同的验证。 This means if the user puts in a wrong number in the new input field, the error will show on every input field.. How can i solve this, i think the name and #ngmodel has to be unique, but i don't know how i can make it unique over here. 这意味着如果用户在新的输入字段中输入了错误的数字,则错误将显示在每个输入字段上。我该如何解决这个问题,我认为名称和#ngmodel必须是唯一的,但我不知道我如何才能在这里变得独一无二。

<form #form="ngForm" class="form">
  <div layout="column" flex *ngFor="let item of numbers; let i = index">

  <div layout="row" flex >
    <mat-form-field class="row-margin" flex>
      <input [(ngModel)]="numbers[i].value" name="test" matInput placeholder="Number input" #test="ngModel" pattern="^[0-9]{3}.[0-9]{2}.[0-9]{2}.[0-9]{2}(\.[0-9]{2})?$" flex>
      <mat-error *ngIf="test.errors?.pattern">No valid pattern</mat-error>
    </mat-form-field>
    <!-- only delete elements if list has more dan one element -->
    <button *ngIf="i >= 1" mat-button (click)="deleteNumberFromList(i)">Delete</button>
  </div>      

</div>

    <mat-dialog-actions class="actions" layout="row">
  <button type="submit" mat-button [disabled]="!form.valid" (click)="add()">Save</button>
    </mat-dialog-actions>
</form>

在此处输入图片说明

#test="ngModel"

This makes every input having template reference of #test so you are duplicating references. 这使每个输入都具有#test模板引用,因此您要复制引用。

Insteed of referencing inputs wrap everything with <form #form="ngForm"> and then check for errors using that form. 在引用inputs指导下,所有内容都用<form #form="ngForm"> ,然后使用该表单检查错误。 It will be something like 它会像

form.controls[controlName].errors 

Also remember that every ngModel input has to have unique name. 还要记住,每个ngModel输入必须具有唯一的名称。 You can generate it using index variable. 您可以使用index变量生成它。

Define array in component and keep pushing in it. 在组件中定义数组并继续推送。

export class AppComponent {
    qtd:any[] = {};
}

id="qtd{{num}}" [(ngModel)]="qtd[num]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM