How to create custom input with ngModel usage
文章目录
-
Create a provider in the custom component.
providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CustomSearchableTextComponent), multi: true } ] -
Override some functions of native input, and update model value inside the writeValue method
// overwrite onTouched: () => void = () => { }; onChange: (_: any) => void = (_: any) => { }; writeValue(value: any): void { if (value !== undefined) { this.searchInput = value; } } // /** // * Registers a callback function that should be called when the control's value changes in the UI. // * @param fn // */ registerOnChange(fn: any): void { this.onChange = fn; } // /** // * Registers a callback function that should be called when the control receives a blur event. // * @param fn // */ registerOnTouched(fn: any): void { this.onTouched = fn; } -
add
ngModelChangeevent handler and callonChangemethodonInputChange(e) { this.onChange(e); }
custom-searchable-text-input.ts
import { Component, OnInit, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-custom-searchable-text',
templateUrl: './custom-searchable-text.component.html',
styleUrls: ['./custom-searchable-text.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomSearchableTextComponent),
multi: true
}
]
})
export class CustomSearchableTextComponent implements OnInit {
searchInput: string;
constructor() { }
ngOnInit(): void {
}
onInputChange(e) {
// async model from outside to inside
this.onChange(e);
}
// overwrite
onTouched: () => void = () => { };
onChange: (_: any) => void = (_: any) => { };
writeValue(value: any): void {
if (value !== undefined) {
this.searchInput = value;
}
}
// /**
// * Registers a callback function that should be called when the control's value changes in the UI.
// * @param fn
// */
registerOnChange(fn: any): void {
this.onChange = fn;
}
// /**
// * Registers a callback function that should be called when the control receives a blur event.
// * @param fn
// */
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
custom-searchable-text-input.html
<input
type="text"
[(ngModel)]="searchInput"
[required]="isRequired"
(ngModelChange)="onInputChange($event)"
/>
Parent reference
<app-custom-searchable-text
[(ngModel)]="searchInput"
#test="ngModel"
></app-custom-searchable-text>

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论