美文网首页
ionic2自定义component:数字输入框

ionic2自定义component:数字输入框

作者: 无比帅气 | 来源:发表于2017-07-24 22:22 被阅读0次

我们平时使用app的时候都会遇到下图的数字控件。最近做ionic2项目的时候遇到一个类似的,就自己写了个控件

WechatIMG4.jpeg

下面贴出代码
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;
    }

}

相关文章

网友评论

      本文标题:ionic2自定义component:数字输入框

      本文链接:https://www.haomeiwen.com/subject/qtsikxtx.html