首页 > 解决方案 > Angular 9 修剪指令

问题描述

我有一个指令应该在输入框中修剪一个值。该指令修剪表单中的值,但是当我提交它时,该值没有被修剪。

// this code works and the value is trimmed after submitting the form
<input type="text" matInput formControlName="adress" oninput="this.value = this.value.trim()">

// this code trim the value on the form but NOT after submitting the form
<input type="text" matInput formControlName="adress" trimvalue>

我在指令中遗漏了什么?

指示:

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
    selector: '[trimvalue]'
})
export class TrimDirective {
    constructor(
        private renderer: Renderer2,
        private elementRef: ElementRef
    ) { }

    @HostListener('input') onInput(event) {
        let value = this.elementRef.nativeElement.value;

        if (value) {
            value = value.trim();
            this.elementRef.nativeElement.value = value.trim();

            this.renderer.setValue(this.elementRef.nativeElement, this.elementRef.nativeElement.value);
        }
    }
}

标签: directiveangular9

解决方案


角度源代码 - setValue()

你可以看到setValue正在醒来node.textContent = value;

  setValue(node: RText, value: string): void {
    node.textContent = value;
  }

并且textContentstring|null

export interface RText extends RNode {
  textContent: string|null;
}

所以,我想setValue()没有像预期的那样工作是因为打字稿的类型在后台出现问题......

你可以修剪它nodeValue

this.elementRef.nativeElement.childNodes.forEach((x: ChildNode, i: number) => {
      if (x.nodeName === '#text') {
        this.elementRef.nativeElement.childNodes[i].nodeValue = this.elementRef.nativeElement.childNodes[i].nodeValue.trim();
      }
    });
  }

推荐阅读