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

Angular 14 如何将用户表单输入数据存入UserService数组?

实现表单数据存入UserService数组的方案

1. 完善UserService,添加用户添加方法

首先给服务添加@Injectable装饰器(否则无法注入到组件),并新增添加用户的方法:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor() {}

  users = [
    {
      fname: 'first',
      lname: 'last',
      email: 'email@email.com',
      password: 'temp12345',
    },
    {
      fname: 'first2',
      lname: 'last2',
      email: 'email2@email.com',
      password: 'abc12345',
    },
  ];

  // 新增添加用户的方法
  addUser(newUser: {fname: string, lname: string, email: string, password: string}) {
    this.users.push(newUser);
  }
}

2. 在LoginComponent中注入UserService并实现提交逻辑

修改组件代码,注入服务并编写表单提交处理方法:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../users.service'; // 根据实际文件路径调整导入

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
  constructor(private userService: UserService) {}

  ngOnInit(): void {}

  displaySignUp: boolean = true;
  displayLogIn: boolean = false;
  displayFrogotPassword: boolean = false;

  fname: string = '';
  lname: string = '';
  email: string = '';
  password: string = '';

  displayHeader(option: string) {
    if (option == 'signUp') {
      this.displaySignUp = true;
      this.displayLogIn = false;
      this.displayFrogotPassword = false;
    } else {
      this.displaySignUp = false;
      this.displayLogIn = true;
      this.displayFrogotPassword = false;
    }
  }

  // 表单提交处理方法
  onSignUpSubmit() {
    const newUser = {
      fname: this.fname,
      lname: this.lname,
      email: this.email,
      password: this.password
    };
    this.userService.addUser(newUser);
    
    // 可选:提交后清空表单并切换到登录界面
    this.fname = '';
    this.lname = '';
    this.email = '';
    this.password = '';
    this.displayHeader('login');
  }
}

3. 给HTML表单添加双向绑定和提交事件

完善模板,给输入框添加双向绑定,给表单绑定提交事件:

<div>
    <div *ngIf="displaySignUp" id="signup">
      <h1>Sign Up for Free</h1>

      <form (ngSubmit)="onSignUpSubmit()">
        <div class="top-row">
          <div class="field-wrap">
            <input
              type="text"
              placeholder="First Name*"
              required
              autocomplete="off"
              [(ngModel)]="fname"
              name="fname"
            />
          </div>

          <div class="field-wrap">
            <input
              type="text"
              placeholder="Last Name*"
              required
              autocomplete="off"
              [(ngModel)]="lname"
              name="lname"
            />
          </div>
        </div>

        <div class="field-wrap">
          <input
            type="email"
            placeholder="Email Address*"
            required
            autocomplete="off"
            [(ngModel)]="email"
            name="email"
          />
        </div>

        <!-- 补充密码输入框 -->
        <div class="field-wrap">
          <input
            type="password"
            placeholder="Password*"
            required
            autocomplete="off"
            [(ngModel)]="password"
            name="password"
          />
        </div>

        <!-- 添加提交按钮 -->
        <button type="submit">Sign Up</button>
      </form>
    </div>
</div>

4. 在模块中导入FormsModule

使用[(ngModel)]需要在组件所属模块中导入FormsModule:

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

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:27:47