首页 > 其他 > 详细

angular 自定义组件和form的formControlName 连用

时间:2021-06-21 23:45:16      阅读:30      评论:0      收藏:0      [点我收藏+]

效果预览

技术分享图片
技术分享图片

TS代码

import { Component, forwardRef, Input, OnInit } from ‘@angular/core‘;
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from ‘@angular/forms‘;

@Component({
    selector: ‘app-number-plus-subtract‘,
    templateUrl: ‘./number-plus-subtract.component.html‘,
    styleUrls: [‘./number-plus-subtract.component.scss‘],
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        multi: true,
        useExisting: forwardRef(() => NumberPlusSubtractComponent)
    }]
})
export class NumberPlusSubtractComponent implements OnInit, ControlValueAccessor {
    inputValue = 1;                 // 初始值

    @Input() defaultValue: number;  // 默认值
    @Input() min: number;           // 最小值
    @Input() max: number;           // 最大值
    @Input() step: number;          // 递增/递减步数
    @Input() dsiabled: boolean;     // 是否可用

    onChange: any = () => { };
    onTouch: () => void = () => null;

    constructor() {

    }

    // 封装组件搭配form的formControlName 使用
    writeValue(obj: any): void {
        this.inputValue = obj;
    }
    registerOnChange(fn: any): void {
        this.onChange = fn;
    }
    registerOnTouched(fn: any): void {
        this.onTouch = fn;
    }


    countSubtract() {
        if (this.dsiabled) {
            return;
        }
        if ((this.min || this.min === 0) && this.min >= (this.inputValue - this.step)) {
            this.inputValue = this.min;
            return;
        }
        this.inputValue = this.inputValue - this.step;
        this.onChange(this.inputValue);
    }

    countPlus() {
        if (this.dsiabled) {
            return;
        }
        if ((this.max || this.max === 0) && this.max <= (this.inputValue + this.step)) {
            this.inputValue = this.max;
            return;
        }
        this.inputValue += this.step;
        this.onChange(this.inputValue);
    }

    setDefaultInfo() {
        if (this.defaultValue || this.defaultValue === 0) {
            this.inputValue = this.defaultValue;
        }

        if (!this.step) {
            this.step = 1;
        }

        if (this.inputValue < this.min) {
            this.inputValue = this.min;
        }
    }

    ngOnInit() {
        this.setDefaultInfo();
    }

}

关键代码

技术分享图片
技术分享图片

angular 自定义组件和form的formControlName 连用

原文:https://www.cnblogs.com/niluiquhz/p/14915542.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!