如何在使用Angular2时在输入类型中实现管道?

时间:2017-02-15 12:27:36

标签: angular

我是angularJS2的新手,我正在尝试在表单的输入类型文本中实现管道。例如,如果我有这样的输入标签

  <input type="text" class="col-lg-7 small rounded form-control" formControlName="firstName" />

我希望在文本字段中输入的值全部为大写,我们可以在表单的输入元素中实现这个吗?

2 个答案:

答案 0 :(得分:2)

无法在输入端使用管道。

但是,您可以在输入法中运行管道。

this.toUpper = new UpperCasePipe().transform(input);

希望有所帮助

答案 1 :(得分:2)

1 - 您无法在输入上使用管道。要实现此类目标,您可以使用(keyup) 事件

<input 
  type="text"
  class="col-lg-7 small rounded form-control" 
  formControlName="firstName" 
  (keyup)="upperValue($event.target.value)">

<强>组件:

upperValue(value: string) {
  this.formGroup.patchValue({
    firstName: value.toUpperCase() 
  });
}

http://example.com/

2 - 如果您想为用户显示原始文本并在“幕后”修改它,您可以创建一个指令:

@Directive({
  selector: '[appUppercase]'
})
export class UppercaseDirective implements OnInit {

  private readonly destroySubject$ = new Subject<void>();

  constructor(
    private readonly ngControl: NgControl
  ) { }

  ngOnDestroy(): void {
    this.destroySubject$.next();
    this.destroySubject$.complete();
  }

  ngOnInit(): void {
    this.ngControl.control.valueChanges.pipe(
      takeUntil(this.destroySubject$)
    ).subscribe(value => {
      const newValue = value.toUpperCase();

      this.ngControl.control.setValue(newValue, {
        emitEvent: false,
        emitModelToViewChange: false,
        emitViewToModelChange: false
      });
    });
  }
}

STACKBLITZ DEMO

3 - 如果要为用户显示已修改的文本并在formControl中将其保持为小写,请修改指令中的以下行:

...
this.elementRef.nativeElement.value = value.toUpperCase();

this.ngControl.control.setValue(value.toLowerCase(), {
  emitEvent: false,
  emitModelToViewChange: false,
  emitViewToModelChange: false
});
...

STACKBLITZ DEMO