Angular 9中如何将ngForm提交的表单数据存入数组?
Hey there! Let's get your form data properly added to that array. The core issue here is that your arraydata variable is declared but never initialized—so when you try to push() to it, you're trying to call a method on undefined, which throws an error. Let's walk through all the fixes step by step:
1. Initialize Your Array
First, make sure you set your array to an empty array when declaring it. This gives it a valid array object to work with:
// Replace this line: // arraydata:formData[]; // With this: arraydata: formData[] = [];
2. Remove Duplicate name Attributes
Looking at your HTML, every input has duplicate name attributes (like name="fullName" written twice). Angular's ngModel relies on unique name attributes to bind data correctly—delete one of each pair:
<!-- Before (duplicate name): --> <input type="text" required ngModel name="fullName" name="fullName" ...> <!-- After (single name): --> <input type="text" required ngModel name="fullName" ...>
3. Add Form Validation Check (Optional but Recommended)
Before pushing data, check if the form is valid to avoid adding incomplete entries. You can also reset the form after submission to give users a clean slate:
data(f: NgForm){ if(f.valid) { // Only proceed if form is valid this.arraydata.push(f.value); f.reset(); // Clear form fields after submission console.log('Updated contact list:', this.arraydata); // Verify in console } }
4. Using Your ContactListService (If Needed)
Since you've injected the ContactListService, you might want to store the data there instead of a component-local array (so you can access it across other components). Here's how to set that up:
Update the Service
Add a method to handle adding contacts in your service:
import { Injectable } from '@angular/core'; import { formData } from './new-contact.component'; // Adjust path to match your setup @Injectable({ providedIn: 'root' }) export class ContactListService { contacts: formData[] = []; addContact(contact: formData) { this.contacts.push(contact); } }
Update the Component
Modify your data method to use the service:
data(f: NgForm){ if(f.valid) { this.contactList.addContact(f.value); // Use service to store data f.reset(); console.log('Service contact list:', this.contactList.contacts); } }
Full Modified Code
Component TypeScript
import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { ContactListService } from '../contact-list.service'; @Component({ selector: 'app-new-contact', templateUrl:'./new-contact.component.html', styleUrls: ['./new-contact.component.css'] }) export class NewContactComponent implements OnInit { arraydata: formData[] = []; constructor(private contactList: ContactListService) { } ngOnInit(): void { } data(f: NgForm){ if(f.valid){ this.arraydata.push(f.value); f.reset(); // Optional: Use service instead // this.contactList.addContact(f.value); console.log('Updated array:', this.arraydata); } } } interface formData{ fullName:string; email:string; phone:number; company:string; address:string; }
Component HTML
<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" 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" 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" class="form-control" id="phone" placeholder="Please Enter Your Phone Number"> </div> </div> <div class="form-group row"> <label for="company" class="col-sm-2 col-form-label">Company</label> <div class="col-sm-10"> <input type="text" required ngModel name="company" class="form-control" id="company" placeholder="Please Enter Your Company Name"> </div> </div> <div class="form-group row"> <label for="address" class="col-sm-2 col-form-label">Address</label> <div class="col-sm-10"> <input type="text" required ngModel name="address" class="form-control" id="address" placeholder="Please Enter Your Address"> </div> </div> <button style="float:right" class="btn btn-primary" type="submit">Create</button> </form>
After making these changes, your form data should be successfully added to the array every time you submit!
内容的提问来源于stack exchange,提问作者Srinivas Neelamraju

