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

Angular带移除选项的多输入字段开发:支持多邮箱添加及移除

Angular 多邮箱输入组件实现方案

组件类 (email-input.component.ts)

import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-email-input',
  templateUrl: './email-input.component.html',
  styleUrls: ['./email-input.component.scss']
})
export class EmailInputComponent {
  emailList: string[] = [];
  emailControl = new FormControl('', [Validators.required, Validators.email]);

  addEmail(): void {
    const email = this.emailControl.value?.trim();
    if (email && this.emailControl.valid && !this.emailList.includes(email)) {
      this.emailList.push(email);
      this.emailControl.reset();
    }
  }

  removeEmail(email: string): void {
    this.emailList = this.emailList.filter(item => item !== email);
  }
}

组件模板 (email-input.component.html)

<div class="email-input-container">
  <div class="email-tags">
    <span *ngFor="let email of emailList" class="email-tag">
      {{ email }}
      <button class="remove-btn" (click)="removeEmail(email)">&times;</button>
    </span>
  </div>
  <input 
    type="email" 
    [formControl]="emailControl"
    placeholder="输入邮箱地址"
    (keyup.enter)="addEmail()"
    class="email-input"
  >
  <button (click)="addEmail()" [disabled]="!emailControl.valid" class="add-btn">添加</button>
</div>

组件样式 (email-input.component.scss)

.email-input-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  align-items: center;

  .email-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .email-tag {
    background-color: #e0e0e0;
    padding: 4px 8px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 6px;

    .remove-btn {
      background: none;
      border: none;
      cursor: pointer;
      font-size: 16px;
      color: #666;
      padding: 0;
      line-height: 1;
    }
  }

  .email-input {
    flex: 1;
    min-width: 200px;
    padding: 4px 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

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

    &:disabled {
      background-color: #6c757d;
      cursor: not-allowed;
    }
  }
}

使用方式

在父组件模板中直接引入组件:

<app-email-input></app-email-input>

功能说明

  • 输入合法邮箱后,按回车或点击「添加」按钮即可将邮箱加入列表
  • 重复邮箱不会被重复添加
  • 点击邮箱标签后的×按钮可移除对应邮箱
  • 输入框自带邮箱格式校验,不合法时「添加」按钮自动禁用

内容的提问来源于stack exchange,提问作者Rajesh M P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:45:28