我正在使用 Angular 版本 9。我创建了一个包含 5 个字段的表单,称为全名、电子邮件、电话、公司、地址。我在表单中使用 ngForm 指令来获取每次提交时提交的数据,并处理 ngSubmit 事件来获取表单数据。但我无法将该对象添加到数组中。如何实现这一目标?这是我的代码...import { Component, OnInit } from '@angular/core';import { NgForm, EmailValidator } from '@angular/forms';import { ContactListService } from '../contact-list.service';import { JsonPipe } from '@angular/common';@Component({ selector: 'app-new-contact', templateUrl:'./new-contact.component.html', styleUrls: ['./new-contact.component.css']})export class NewContactComponent implements OnInit { constructor(private contactList: ContactListService) { } arraydata:formData[]; ngOnInit(): void { } data(f:NgForm){ this.arraydata.push(f.value); }}interface formData{ fullName:string; email:string; phone:number; company:string; address:string;}<form #f="ngForm" (ngSubmit)="data(f)"> <div class="form-group row"> <label for="fullName" class="col-sm-2 col-form-label">Full Name</label> <div class="col-sm-10"> <input type="text" required ngModel name="fullName" name="fullName" class="form-control" id="fullName" placeholder="Please Enter Your Full Name"> </div> </div> <div class="form-group row"> <label for="email" class="col-sm-2 col-form-label">Email</label> <div class="col-sm-10"> <input type="email" required ngModel name="email" name="email" class="form-control" id="email" placeholder="Please Enter Your Email"> </div> </div> <div class="form-group row"> <label for="phone" class="col-sm-2 col-form-label">Phone</label> <div class="col-sm-10"> <input type="number" required ngModel name="phone" name="phone" class="form-control" id="phone" placeholder="Please Enter Your Phone Number"> </div>
2 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
您尚未初始化数组 arraydata。因此它在您的组件中未定义。
只需将 arraydata 初始化为一个空数组,如下所示
arraydata:formData[] =[]
- 2 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消