简体   繁体   English

Angular 7 Dynamic Creating表格,带有ngFor和ngModel,带有验证(或ngFrom)

[英]Angular 7 Dynamic Creating form with ngFor and ngModel with validation (or ngFrom)

I am trying to create a table like input form in Angular. 我正在尝试在Angular中创建一个类似输入表单的表。

My current solution is like this: 我目前的解决方案是这样的:

html: HTML:

<form (ngSubmit)="doSomething()">
<table>
    <thead>
        <tr>First Name</tr>
        <tr>Last Name</tr>
        <tr>Phone Number</tr>
    </thead>
    <tbody>
        <tr *ngFor="let person of team"></tr>
        <td><input type="text" [(ngModel)]="person.first_name" [ngModelOptions]="{standalone: true}" required></td>
        <td><input type="text" [(ngModel)]="person.last_name" [ngModelOptions]="{standalone: true}" required></td>
        <td><input type="text" [(ngModel)]="person.phone" [ngModelOptions]="{standalone: true}" required></td>
    </tbody>
</table>
<button (click)="addNewEntry()"></button>
<button type="submit">Submit</button>

ts: TS:

team : new Array()
addNewEntry(){
    this.team.push({
        'first_name':'',
        'last_name':'',
        'phone':null})
}

doSomething(){
};

However, if I do it this way, the 'required' validator does not work on clicking the Submit button. 但是,如果我这样做,“必需的”验证器在单击“提交”按钮时不起作用。

I tried couple of ways: 我尝试了几种方法:

  1. instead of setting [ngModelOptions]="{standalone: true}" , I tried name='person:{{$index}}' . 而不是设置[ngModelOptions] =“{standalone:true}” ,我尝试了name ='person:{{$ index}}' Does not work. 不行。

  2. Tried to set up a ngForm and instead of using ngModel , use formControlName . 尝试设置ngForm而不是使用ngModel ,使用formControlName I can't figure out how to dynamically create formControlName and validate them. 我无法弄清楚如何动态创建formControlName并验证它们。

May I ask if there is a way to get this done properly? 请问是否有办法正确完成这项工作?

Thanks! 谢谢!

Your best bet is to use Angular ReactiveFormsModule. 您最好的选择是使用Angular ReactiveFormsModule。 ReactiveFormsModule support FormArray and will make it easy to perform validation and get the form item values. ReactiveFormsModule支持FormArray,可以轻松执行验证并获取表单项值。

For reference, check out: 供参考,请查看:

  1. https://angular.io/guide/reactive-forms https://angular.io/guide/reactive-forms
  2. https://stackoverflow.com/a/48527939/9194488 https://stackoverflow.com/a/48527939/9194488

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

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