我们平时使用app的时候都会遇到下图的数字控件。最近做ionic2项目的时候遇到一个类似的,就自己写了个控件
下面贴出代码
html如下
<div class="numSelector">
<div class="minus" (click)="minus()" tappable>
<ion-icon name="ios-remove-outline"></ion-icon>
</div>
<div class="num">
<ion-input type="tel" (ionChange)='inputChange()' [(ngModel)]="value"></ion-input>
</div>
<div class="add" (click)="add()" tappable>
<ion-icon name="ios-add-outline"></ion-icon>
</div>
</div>
ts代码如下
import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => HighlightDirective),
multi: true
};
@Component({
selector: 'custom-input',
templateUrl: 'numInput.html',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class HighlightDirective implements ControlValueAccessor {
//The internal data model
private innerValue: any = '';
//Placeholders for the callbacks which are later provided
//by the Control Value Accessor
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
//get accessor
get value(): any {
return this.innerValue;
};
//set accessor including call the onchange callback
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
add () {
this.value ++;
this.onTouchedCallback();
}
minus () {
if(this.value > 0){
this.value --;
this.onTouchedCallback();
}
}
inputChange () {
if(isNaN(this.value)){
this.value = 0;
console.log(this.value)
}
}
//Set touched on blur
onBlur() {
this.onTouchedCallback();
}
//From ControlValueAccessor interface
writeValue(value: any) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
//From ControlValueAccessor interface
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
//From ControlValueAccessor interface
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}