Browse Source

refactor(core): add valueFn and valueLimitFn functions to ng-model.component

pull/2605/head
mehmet-erim 7 years ago
parent
commit
628675e9df
  1. 49
      npm/ng-packs/packages/core/src/lib/abstracts/ng-model.component.ts

49
npm/ng-packs/packages/core/src/lib/abstracts/ng-model.component.ts

@ -1,27 +1,48 @@
import { ControlValueAccessor } from '@angular/forms'; import { ControlValueAccessor } from '@angular/forms';
import { ChangeDetectorRef, Component, Injector, Input, Type } from '@angular/core'; import { ChangeDetectorRef, Component, Injector, Input } from '@angular/core';
@Component({ selector: 'abp-abstract-ng-model', template: '' }) // Not an abstract class on purpose. Do not change!
export class AbstractNgModelComponent<T = any> implements ControlValueAccessor { // tslint:disable-next-line: use-component-selector
@Input() disabled: boolean; @Component({ template: '' })
export class AbstractNgModelComponent<T = any, U = T> implements ControlValueAccessor {
protected _value: T;
protected cdRef: ChangeDetectorRef;
onChange: (value: T) => {};
onTouched: () => {};
@Input()
disabled: boolean;
@Input()
readonly: boolean;
@Input()
valueFn: (value: U, previousValue?: T) => T = value => (value as any) as T;
@Input()
valueLimitFn: (value: T, previousValue?: T) => any = value => false;
@Input()
set value(value: T) {
value = this.valueFn((value as any) as U, this._value);
if (this.valueLimitFn(value, this._value) !== false || this.readonly) return;
@Input() set value(value: T) {
this._value = value; this._value = value;
this.notifyValueChange(); this.notifyValueChange();
} }
get value(): T { get value(): T {
return this._value; return this._value || this.defaultValue;
} }
onChange: (value: T) => {}; get defaultValue(): T {
onTouched: () => {}; return this._value;
}
protected _value: T;
protected cdRef: ChangeDetectorRef;
constructor(public injector: Injector) { constructor(public injector: Injector) {
this.cdRef = injector.get<ChangeDetectorRef>(ChangeDetectorRef as Type<ChangeDetectorRef>); // tslint:disable-next-line: deprecation
this.cdRef = injector.get(ChangeDetectorRef);
} }
notifyValueChange(): void { notifyValueChange(): void {
@ -31,8 +52,8 @@ export class AbstractNgModelComponent<T = any> implements ControlValueAccessor {
} }
writeValue(value: T): void { writeValue(value: T): void {
this._value = value; this._value = this.valueLimitFn(value, this._value) || value;
setTimeout(() => this.cdRef.detectChanges(), 0); setTimeout(() => this.cdRef.markForCheck(), 0);
} }
registerOnChange(fn: any): void { registerOnChange(fn: any): void {

Loading…
Cancel
Save