我有以下输入元素:
<input
range
[btnClass]="'close_input_button'"
type="text"
class="reset-border-right"
formControlName="parentId1Name"
/>
如您所见,我使用指令:
range [btnClass]="'close_input_button'"
指令如下:
@Directive({
selector: "[range]"
})
export class RangeDirective implements OnInit {
@HostListener("change", ["$event"]) ngOnChanges(value: any) {
console.log(value);
}
}
为什么当我使用反应形式为输入设置新值时,它会触发指令中的更改事件?
this.form.get("parentId1Name").setValue('New value');
完整指令为:
import {
Input,
HostListener,
OnInit,
OnChanges,
SimpleChanges
} from "@angular/core";
import { Renderer2 } from "@angular/core";
import { ElementRef } from "@angular/core";
import { Directive } from "@angular/core";
@Directive({
selector: "[range]"
})
export class RangeDirective implements OnInit, OnChanges {
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
readonly _elements = ["INPUT", "SELECT", "TEXTAREA"];
private newDomElement: any;
@Input() btnClass: string;
@Input() model: any;
@Input() position: string = "right";
ngOnInit(): void {
const parent = this.elementRef.nativeElement.parentNode;
const reference = this.elementRef.nativeElement;
this.elementRef.nativeElement.parentNode.style.position = "relative";
this.newDomElement = this.createButton();
this.renderer.insertBefore(parent, this.newDomElement, reference);
}
@HostListener("keyup", ["$event"]) ngKeyup(value: any) {
this.eventHandler(value);
}
@HostListener("change", ["$event"]) ngChange(value: any) {
this.eventHandler(value);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.input) {
console.log("input changed");
}
}
eventHandler(value: any) {
if (!value.srcElement) return;
const _value = value.srcElement.value.toString().trim();
if (_value) {
this.newDomElement.style.display = "flex";
} else {
this.newDomElement.style.display = "none";
}
}
createButton() {
let closeButton = document.createElement("div");
closeButton.innerHTML = '<i class="material-icons">clear</i>';
closeButton.className = this.btnClass;
closeButton.className += " " + this.position;
closeButton.style.display = "none";
closeButton.onclick = () => {
closeButton.style.display = "none";
this.elementRef.nativeElement.value = null;
};
return closeButton;
}
}
答案 0 :(得分:3)
您需要输入的输入属性,然后使用ngOnChanges钩子告诉输入属性何时更改。
@Directive({
selector: '[range]'
})
export class RangeDirective implements OnChanges {
@Input() public range: any;
@Input() public input: any;
ngOnChanges(changes: SimpleChanges){
if(changes.input){
console.log('input changed');
}
}
}