Angular2 Pipe无法删除输入中的字母
Angular2 Pipe can't remove letters in input
我正在尝试在 Angular2 中构建管道。 "yearPipe" 应该只允许数字并将输入长度限制为 4。我看到一些非常奇怪的行为。
<input type="text" [ngModel]="customer.year | year" (ngModelChange)="customer.year = $event">
烟斗:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'year' })
export class YearPipe implements PipeTransform {
transform(val: string): string {
if (val){
let outputValue = val;
outputValue = outputValue.replace(/\D/g, "");
outputValue = outputValue.substring(0, outputValue.length < 4 ? outputValue.length : 4);
console.log(outputValue);
return outputValue
}
return "";
}
}
我确定我的管道不能删除值,只能添加值。因此,将字符数限制为 4 或删除非数字的尝试失败了。如果我将另一个变量数据绑定到同一个 "customer.year" 字段,它会显示管道值。
示例:
<input type="text" [ngModel]="customer.year | year" (ngModelChange)="customer.year = $event">
{{ customer.year }}
如果我输入 2009asdf,{{ customer.year }} 将显示 2008,而输入将显示 2008asdf。这里的示例:https://plnkr.co/edit/JAxA777p1dX8u2RpmvSA?p=preview 似乎能够去除数字,所以我有点困惑。它的实现与我的管道相同,所以我怀疑版本问题。我目前正在使用 RC5 和 CLI。
看来我们需要尝试一些魔法:)
import { Pipe, PipeTransform, WrappedValue } from '@angular/core';
@Pipe({ name: 'year'})
export class YearPipe implements PipeTransform {
transform(val: string): any {
if(!val) return '';
return WrappedValue.wrap(val.replace(/\D/g, '')
.substring(0, val.length < 4 ? val.length : 4))
}
}
我认为它应该也适用于 RC.5
我正在尝试在 Angular2 中构建管道。 "yearPipe" 应该只允许数字并将输入长度限制为 4。我看到一些非常奇怪的行为。
<input type="text" [ngModel]="customer.year | year" (ngModelChange)="customer.year = $event">
烟斗:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'year' })
export class YearPipe implements PipeTransform {
transform(val: string): string {
if (val){
let outputValue = val;
outputValue = outputValue.replace(/\D/g, "");
outputValue = outputValue.substring(0, outputValue.length < 4 ? outputValue.length : 4);
console.log(outputValue);
return outputValue
}
return "";
}
}
我确定我的管道不能删除值,只能添加值。因此,将字符数限制为 4 或删除非数字的尝试失败了。如果我将另一个变量数据绑定到同一个 "customer.year" 字段,它会显示管道值。
示例:
<input type="text" [ngModel]="customer.year | year" (ngModelChange)="customer.year = $event">
{{ customer.year }}
如果我输入 2009asdf,{{ customer.year }} 将显示 2008,而输入将显示 2008asdf。这里的示例:https://plnkr.co/edit/JAxA777p1dX8u2RpmvSA?p=preview 似乎能够去除数字,所以我有点困惑。它的实现与我的管道相同,所以我怀疑版本问题。我目前正在使用 RC5 和 CLI。
看来我们需要尝试一些魔法:)
import { Pipe, PipeTransform, WrappedValue } from '@angular/core';
@Pipe({ name: 'year'})
export class YearPipe implements PipeTransform {
transform(val: string): any {
if(!val) return '';
return WrappedValue.wrap(val.replace(/\D/g, '')
.substring(0, val.length < 4 ? val.length : 4))
}
}
我认为它应该也适用于 RC.5