【问题标题】:how changing the output of angular2 ngModel through ControlValueAcessor如何通过 ControlValueAcessor 改变 angular2 ngModel 的输出
【发布时间】:2016-10-10 08:29:43
【问题描述】:

我想编写一个非常简单的 Angular2 组件,它基本上从父视图中获取 ngControlngModel。来自父级的输入是Date,在组件内部我将其转换为String。作为输出,我想将String 绑定回Date

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
    NG_VALUE_ACCESSOR, {
        useExisting: forwardRef(() => PtDatepicker),
        multi: true
    });

@Component({
    moduleId: module.id,
    selector: "pt-datepicker",
    template: `<input type="date" [(ngModel)]="value">`,
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})

export class PtDatepicker implements ControlValueAccessor {

    //The internal data model
    private _value:string = '';

    //Placeholders for the callbacks
    private _onTouchedCallback:() => void = noop;
    private _onChangeCallback:(_:any) => void = noop;

    //get accessor
    get value():any {
        return this._value;
    };

    //set accessor including call the onchange callback
    set value(v:any) {
        if (v !== this._value) {
            this._value = v;
            this._onChangeCallback(v);
        }
    }

    //From ControlValueAccessor interface
    writeValue(value:Date) {
        const str = value ? moment(value).format("YYYY-MM-DD") : "";
        this._value = str;
    }

    //From ControlValueAccessor interface
    registerOnChange(fn:any) {
        this._onChangeCallback = fn;
    }

    //From ControlValueAccessor interface
    registerOnTouched(fn:any) {
        this._onTouchedCallback = fn;
    }
}

这样调用:

<pt-datepicker [ngModel]="plan.validUntil" ngControl="validUntil"></pt-datepicker>

我是 Angular2 的新手。感谢帮助!干杯

【问题讨论】:

    标签: angular angular2-directives angular2-forms


    【解决方案1】:

    我认为您错过了以下双向绑定:

    <pt-datepicker [(ngModel)]="plan.validUntil"
            ngControl="validUntil"></pt-datepicker>
    

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      相关资源
      最近更新 更多