如何用NG-ZORRO创建可输入多字符串并生成JSON数组的输入组件?
基于NG-ZORRO的多字符串转JSON数组输入组件实现
下面是一个可直接复用的实现方案,包含输入、添加、删除标签,以及实时生成JSON数组的功能:
组件模板 (multi-string-to-json.component.html)
<div class="multi-input-container"> <nz-input-group [nzSuffix]="suffixTemplate"> <input nz-input [(ngModel)]="currentInput" placeholder="输入字符串后回车或点击添加" (keyup.enter)="addItem()" /> </nz-input-group> <ng-template #suffixTemplate> <button nz-button nzType="primary" (click)="addItem()" nzSize="small"> <i nz-icon nzType="plus"></i> </button> </ng-template> <div class="tag-list" *ngIf="items.length > 0"> <nz-tag *ngFor="let item of items; let i = index" [nzColor]="'blue'" (nzOnClose)="removeItem(i)" nzClosable > {{ item }} </nz-tag> </div> <div class="json-output" *ngIf="items.length > 0"> <h4>JSON 输出:</h4> <pre>{{ jsonOutput }}</pre> </div> </div>
组件逻辑 (multi-string-to-json.component.ts)
import { Component } from '@angular/core'; @Component({ selector: 'app-multi-string-to-json', templateUrl: './multi-string-to-json.component.html', styleUrls: ['./multi-string-to-json.component.less'] }) export class MultiStringToJsonComponent { currentInput = ''; items: string[] = []; addItem(): void { const trimmedInput = this.currentInput.trim(); // 过滤空输入和重复项 if (trimmedInput && !this.items.includes(trimmedInput)) { this.items.push(trimmedInput); this.currentInput = ''; } } removeItem(index: number): void { this.items.splice(index, 1); } // 实时生成格式化的JSON数组 get jsonOutput(): string { return JSON.stringify(this.items, null, 2); } }
样式优化 (multi-string-to-json.component.less)
.multi-input-container { padding: 16px; .tag-list { margin-top: 12px; .ant-tag { margin-right: 8px; margin-bottom: 8px; } } .json-output { margin-top: 16px; pre { background-color: #f5f5f5; padding: 12px; border-radius: 4px; white-space: pre-wrap; word-break: break-all; } } }
使用方式
在父组件模板中直接引入组件:
<app-multi-string-to-json></app-multi-string-to-json>
核心功能说明
- 输入添加:支持回车或点击加号按钮添加字符串,自动去重并过滤空值
- 标签管理:已添加的字符串以可关闭标签展示,点击叉号可删除对应项
- JSON实时生成:根据已添加的字符串自动生成格式化后的JSON数组,可直接复制使用
可选扩展
- 允许开启/关闭重复项校验
- 支持自定义标签颜色或样式
- 添加输入格式验证(如邮箱、手机号等)
- 支持一键清空所有项
内容的提问来源于stack exchange,提问作者syntaxerror1874
相关产品推荐
相关产品推荐

