首页 > 解决方案 > 角度 texarea 到阵列管道

问题描述

我有 textarea 用于在我的应用程序的许多页面上显示数组中的行(和长度),这与toArray().要显示的字符串。

是否有任何管道我可以在每个组件上使用toArray函数来将数组转换为带有新行('\n')的字符串以用于显示/编辑目的,并将其转换回 API 的数组?

HTML

<textarea class="form-control" rows="3" [(ngModel)]="item.color" (ngModelChange)="toArray($event)"></textarea>

转换为数组(类似类型的多个函数)

  colorArray(value: string): void {
    this.item.color = value.split(/[\r\n]+/);
  }
  patternArray(value: string): void {
    this.item.pattern= value.split(/[\r\n]+/);
  }
  ...

物品

{
 name : 'event',
 color: ['red','black','blue'] 
}

标签: angulartypescript

解决方案


您可以创建一个自定义 textarea 组件,将此正则表达式应用于输入并显示它。另外,输出总是可以是一个数组(或任何你想要的)。

//textareaComponent.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-textarea',
  template: `
    <textarea clas="form-control" rows="3" [(ngModel)]="_color" (ngModelChange)="_onColorsChange()"></textarea>
  `
})
export class TextareaComponent {
  @Input() set colors(value: string[]) {//receives an array of colors and converts it to a string
    this._color = value.join('\n');
  }
  @Output() $onColorsChange = new EventEmitter<string[]>();//emits an array
  public _color: string = ''

  public _onColorsChange(): void {//emits an array to the parent component
    this.$onColorsChange.emit(_color.split(/[\r\n]+/));
  }
}

//ParentComponent.ts
@Component({
  selector: 'app',
  template: `
    <app-textarea
      [colors]="arrayOfColors"
      ($onColorsChange)="doSomethingWithTheArrayOfColors(colors)"></app-texttextarea>
  `
})
export class ParentComponent {
  public arrayOfColors: string[];

  public doSomethingWithTheArrayOfColors(colors: string[]): void {
    console.log(colors);//should print an array on every change on the textarea
  }

推荐阅读