如何解决清除按钮作为指令或角度为2-8的组件
我想在所有输入上放置一个清晰的图标/按钮。是否可以将该组件用作具有清除按钮HTML的属性,因为该组件将在所有输入上用作属性选择器
import { Component,OnInit,Input } from '@angular/core';
@Component({
selector: '[appClearInput]',templateUrl: './clear-input.component.html',styleUrls: ['./clear-input.component.scss'],})
export class ClearInputComponent implements OnInit {
@input() appClearInput: any;
@input() inputs: any;
constructor() {
// console.log(this.inputs);
}
ngOnInit(): void {}
ngAfterViewInit() {
setTimeout(() => {
console.log(this.inputs);
});
}
clearValue() {
this.inputs.value = '';
}
}`
//ClearInputComponent HTML
<button
mat-button
matSuffix
mat-icon-button
aria-label="Clear"
(click)="clearValue()"
>
<mat-icon style="font-size: 18px;">close</mat-icon>
</button>
//Using component as attribute
<mat-form-field fxFlex [ngClass.gt-xs]="'min-ctrl'">
<input
matInput
type="text"
placeholder="Invoice No"
formControlName="invoiceNo"
#inputpurchaseInvoiceNo
maxlength="80"
[appHighlight]="'yellow'"
[appClearInput]="inputpurchaseInvoiceNo"
/>
解决方法
import {
Component,OnInit,Input,ElementRef,Renderer2,ViewChild,AfterViewInit,HostListener,} from '@angular/core';
@Component({
selector: 'input[type="text"],input[type="password"],input[type="number"],input[type="text"][ngModel]',templateUrl: './clear-input.component.html',styleUrls: ['./clear-input.component.scss'],})
export class ClearInputComponent implements AfterViewInit {
constructor(private el: ElementRef,private renderer: Renderer2) {}
ngAfterViewInit() {
const clearInputBtn = document.getElementById(
'food-name-val'
) as HTMLInputElement;
this.renderer.appendChild(
this.el.nativeElement.parentElement,clearInputBtn
);
this.renderer.listen(clearInputBtn,'click',() => {
this.el.nativeElement.value = '';
});
}
@HostListener('focus') onFocus() {
this.el.nativeElement.select();
}
}
<button
#clearInputBtn
id="food-name-val"
mat-button
matSuffix
mat-icon-button
aria-label="Clear"
class="icon-close"
>
<mat-icon style="font-size: 18px;">close</mat-icon>
</button>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。