Angular 2+ 输入元素的自定义指令 - 如何检测重置调用
Angular 2+ custom directive for a input element - how to detect a reset call
我为输入元素构建了自定义指令。这是一个搜索指令,给定一个项目输入 returns 一个输出,这些项目根据搜索字符串过滤。
<input pieSearch placeholder='Search' [attribute]='"label"' [formControl]='search'
[items]='widgetOfSelectedType' (filterEvent)='filterWidgets($event)'>
在幕后,我只是使用一个 Hostlistener,然后调用一个管道。因此:
@HostListener('keyup', ['$event.target.value']) onKeyUp(value) {
this.searchTerm = value;
this.applyFilter();
}
当我想重置我的输入时,这适用于所有预期的事情 this.search.reset()
。这是有道理的,因为这不是在输入字段中键入的用户,因此不会被 Hostlistener 捕获。
所以我想问大家一个问题,你们会怎么做?
我已经为您创建了一个简单的 resetSpy 指令。你可以注入 NgControl 指令来访问底层的 FormControl 指令。
那么只需创建我们自己的重置流即可。我们正在将表单值更改映射到其原始状态。如果控件从 not pristine 变为 pristine,则意味着表单已重置。
import { Directive, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import {map, pairwise, startWith, filter} from 'rxjs/operators';
@Directive({
selector: '[resetSpy]',
})
export class ResetSpyDirective {
@Output() reset = new EventEmitter<void>();
subscription: Subscription;
constructor(private ngControl: NgControl) { }
ngOnInit() {
const reset$ = this.ngControl.control.valueChanges.pipe(
map(v => this.ngControl.pristine),
startWith(this.ngControl.pristine),
pairwise(),
filter(([from, to]) => !from && to)
);
this.subscription = reset$.subscribe(() => this.reset.emit());
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
我为输入元素构建了自定义指令。这是一个搜索指令,给定一个项目输入 returns 一个输出,这些项目根据搜索字符串过滤。
<input pieSearch placeholder='Search' [attribute]='"label"' [formControl]='search'
[items]='widgetOfSelectedType' (filterEvent)='filterWidgets($event)'>
在幕后,我只是使用一个 Hostlistener,然后调用一个管道。因此:
@HostListener('keyup', ['$event.target.value']) onKeyUp(value) {
this.searchTerm = value;
this.applyFilter();
}
当我想重置我的输入时,这适用于所有预期的事情 this.search.reset()
。这是有道理的,因为这不是在输入字段中键入的用户,因此不会被 Hostlistener 捕获。
所以我想问大家一个问题,你们会怎么做?
我已经为您创建了一个简单的 resetSpy 指令。你可以注入 NgControl 指令来访问底层的 FormControl 指令。
那么只需创建我们自己的重置流即可。我们正在将表单值更改映射到其原始状态。如果控件从 not pristine 变为 pristine,则意味着表单已重置。
import { Directive, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import {map, pairwise, startWith, filter} from 'rxjs/operators';
@Directive({
selector: '[resetSpy]',
})
export class ResetSpyDirective {
@Output() reset = new EventEmitter<void>();
subscription: Subscription;
constructor(private ngControl: NgControl) { }
ngOnInit() {
const reset$ = this.ngControl.control.valueChanges.pipe(
map(v => this.ngControl.pristine),
startWith(this.ngControl.pristine),
pairwise(),
filter(([from, to]) => !from && to)
);
this.subscription = reset$.subscribe(() => this.reset.emit());
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}