directive - 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);
}
}
}
解决方案
你可以看到setValue
正在醒来node.textContent = value;
setValue(node: RText, value: string): void {
node.textContent = value;
}
并且textContent
是string|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();
}
});
}
推荐阅读
- reactjs - React native - 在 this.props 之后返回一个字符串
- python - 如何打印动态变量?
- kubernetes - Istio 检查已安装的内容
- google-pagespeed - 4种场景下的累积布局偏移为0?
- c - 如何通过启用 modminer 选项交叉编译 arm 32 位的 cgminer 代码?
- math - 以二进制形式连接前 n 个数字,转换为以 10 为基数
- ios - SwiftUI ForEach 中的动态绑定字段
- java - 从中选择随机值
使用硒的下拉菜单? - javascript - Javascript - 更改驻留在数组中的对象的属性是否会将数组标记为脏?
- sql - Sql Server:在保留行分组的同时对数据集进行分区