You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Angular 4代码:实现双文本框数据添加至FormArray的功能

Angular 4: Implement FormArray to Add Entries from Two Textboxes

Hey there, I've got you covered with a complete, easy-to-follow implementation for this requirement. We'll use Angular's reactive forms (since FormArray is part of this module) to build the functionality where you can add entries from two textboxes to a list below. Let's break it down step by step.


1. Component Class (TypeScript)

First, we'll set up the component logic—importing necessary modules, initializing the form structure, and writing the method to add entries to the FormArray.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';

@Component({
  selector: 'app-entry-adder',
  templateUrl: './entry-adder.component.html',
  styleUrls: ['./entry-adder.component.css']
})
export class EntryAdderComponent implements OnInit {
  entryForm: FormGroup;
  // Temporary variables to hold input values before adding to the array
  tempField1: string = '';
  tempField2: string = '';

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    // Initialize the form with an empty FormArray to store entries
    this.entryForm = this.fb.group({
      entries: this.fb.array([])
    });
  }

  // Getter for easy access to the FormArray in the template
  get entries(): FormArray {
    return this.entryForm.get('entries') as FormArray;
  }

  // Method to add the input values to the FormArray
  addEntry() {
    // Basic validation to ensure both fields aren't empty
    if (this.tempField1.trim() && this.tempField2.trim()) {
      // Create a new FormGroup for the entry with two form controls
      const newEntry = this.fb.group({
        field1: [this.tempField1],
        field2: [this.tempField2]
      });

      // Push the new entry to the FormArray
      this.entries.push(newEntry);

      // Clear the textboxes after adding the entry
      this.tempField1 = '';
      this.tempField2 = '';
    }
  }
}

2. Template (HTML)

Next, we'll build the UI with two textboxes, an add button, and a section to display all added entries.

<div class="entry-container" [formGroup]="entryForm">
  <!-- Input Section -->
  <div class="input-group">
    <input 
      type="text" 
      placeholder="Enter Field 1 value" 
      [(ngModel)]="tempField1" 
      name="tempField1"
      class="form-input"
    >
    <input 
      type="text" 
      placeholder="Enter Field 2 value" 
      [(ngModel)]="tempField2" 
      name="tempField2"
      class="form-input"
    >
    <button (click)="addEntry()" class="add-btn">Add Entry</button>
  </div>

  <!-- Entries List -->
  <div class="entries-list" *ngIf="entries.length > 0">
    <h3>Added Entries:</h3>
    <div class="entry-item" *ngFor="let entry of entries.controls; let i = index">
      <div formGroupName="{{i}}">
        <span><strong>Entry {{i+1}}:</strong></span>
        <span>Field 1: {{entry.get('field1').value}}</span>
        <span>Field 2: {{entry.get('field2').value}}</span>
      </div>
    </div>
  </div>
</div>

3. Import Required Modules in Your App Module

Don't forget to import ReactiveFormsModule (for reactive form directives) and FormsModule (for ngModel) in your root module (like AppModule):

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule } from '@angular/forms';

import { EntryAdderComponent } from './entry-adder/entry-adder.component';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    EntryAdderComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4. Optional: Basic CSS for Better UI

Add this simple CSS to make the interface look cleaner:

.entry-container {
  max-width: 600px;
  margin: 2rem auto;
  padding: 1.5rem;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 1.5rem;
}

.form-input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.add-btn {
  padding: 0.5rem 1rem;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-btn:hover {
  background-color: #0056b3;
}

.entries-list {
  margin-top: 2rem;
}

.entry-item {
  padding: 0.8rem;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 0.5rem;
  display: flex;
  gap: 1rem;
  align-items: center;
}

Quick Explanation:

  • We use ngModel to bind the textboxes to temporary variables in the component.
  • When you click "Add Entry", we validate the inputs, create a new FormGroup for the entry, push it to the FormArray, then clear the textboxes.
  • The template uses *ngFor to loop through the FormArray controls and display each entry's values dynamically.

内容的提问来源于stack exchange,提问作者venkatesh pakanati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:23:21