这个问题符合。对我来说 clearInput 没有绑定到您的 inputVal 它只是取一个值并在指令中相应地采取行动。
对于您的工作方法,您需要在指令中完整引用 inputVal。
现在它只是一个原始值,这就是为什么当你将值更改为 null 时,它只是在指令级别。
[编辑]
试试下面的代码。 - 当您使用 ngmodel 时,我们需要 ngmodel 的参考
<div class="input">
<input matInput clearInput [clearInput]= "value" #inputVal type="text" placeholder="Clearable input" [(ngModel)]="value" />
<div class="alwaysCloseButtonWillBethere"
matSuffix >Close</div>
</div>
clear 指令 -- 只是我采用了一个像 html 一样的常量,就像 div[input , close] 当你点击关闭时输入会变空
import { Directive, OnChanges, Input, HostListener, ElementRef, Renderer2, SimpleChanges, OnInit, OnDestroy} from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[clearInput]',
exportAs: 'clearInput'
})
export class ClaerinputDirective implements OnChanges , OnInit , OnDestroy{
@Input('clearInput') inputValue: any;
constructor(private el: ElementRef, private renderer:Renderer2 , private model: NgModel) {
}
ngOnInit(){
this.el.nativeElement.parentNode.children[1].addEventListener('click', () =>{
this.model.control.reset();
})
}
ngOnChanges(changes: SimpleChanges){
if(changes.inputValue){
if(this.inputValue){
this.renderer.setStyle(this.el.nativeElement.parentNode.children[1], 'display', 'block');
}
else {
this.renderer.setStyle(this.el.nativeElement.parentNode.children[1], 'display', 'none');
}
}
}
ngOnDestroy() {
this.el.nativeElement.parentNode.children[1].removeEventListener('click',null
);
}
}
如果 dom 节点不是静态的,则根据类名在其下方使用我已取的类名 --- alwaysCloseButtonWillBethere
import { Directive, OnChanges, Input, HostListener, ElementRef, Renderer2, SimpleChanges, OnInit, OnDestroy} from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[clearInput]',
exportAs: 'clearInput'
})
export class ClaerinputDirective implements OnChanges , OnInit , OnDestroy{
@Input('clearInput') inputValue: any;
nodeToHideAndShow: HTMLElement;
constructor(private el: ElementRef, private renderer:Renderer2 , private model: NgModel) {
}
getNode(){
if(!this.nodeToHideAndShow){
this.nodeToHideAndShow = this.el.nativeElement.parentNode.querySelector('.alwaysCloseButtonWillBethere');
}
}
ngOnInit(){
this.getNode();
if(!this.nodeToHideAndShow){
// alert('Add a class alwaysCloseButtonWillBethere')
} else {
console.log('d');
this.nodeToHideAndShow.addEventListener('click', () => {
this.model.control.reset();
})
}
}
ngOnChanges(changes: SimpleChanges){
if(changes.inputValue){
this.getNode();
if(this.inputValue){
this.renderer.setStyle( this.nodeToHideAndShow, 'display', 'block');
}
else {
this.renderer.setStyle( this.nodeToHideAndShow, 'display', 'none');
}
}
}
ngOnDestroy() {
if( this.nodeToHideAndShow){
this.nodeToHideAndShow.removeEventListener('click',null);
}
}
}