angular - 角度 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']
}
解决方案
您可以创建一个自定义 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
}
推荐阅读
- azure - 如何在 Github 源码中使用应用服务的部署槽
- php - 如何通过我的 ODBC for MSSQL 成功使用 PDO?
- reactjs - 如何声明一个全局变量并在 ReactJS 的所有其他模块中访问它?
- java - 如何在java中获取原始对象检查器的字段名称
- c - 使用在运行时设置的变量来指定字符数组的大小
- build.gradle - Gradle sync failed: CreateProcess error=2, 系统找不到指定的文件
- c++ - 右键单击文档图标时如何获取上下文菜单项列表
- .net - 授权 Web 应用程序的用户并允许他们访问 API 服务
- elasticsearch - 比较两个数字字段elasticsearch
- nativescript - ScrollView 内带有 ngFor 的 StackLayout