Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

controlvalueaccessor - writeValue not called Angular custom form control

I have several custom form control components in my app so I've implemented a base component that implements the ControlValueAccessor.

export class BaseControlValueAccessor<T> implements ControlValueAccessor, OnInit {
    @Input()
    disabled: boolean;

    @Input()
    required = false;

    @Input()
    label = '';

    @Input()
    name = '';

    @Input()
    placeholder = '';

    @Input()
    value: T;

    constructor(public ngControl: NgControl) {
        if (ngControl) {
            ngControl.valueAccessor = this;
        }
    }

    public onChange(newVal: T) {}
    public onTouched(_?: any) {}

    public writeValue(obj: T) {
        this.value = obj;
        console.log(obj); // <------------ 
    }

    public registerOnChange(fn: any) {
        this.onChange = fn;
    }

    public registerOnTouched(fn: any) {
        this.onTouched = fn;
    }

    public setDisabledState?(isDisabled: boolean) {
        this.disabled = isDisabled;
    }
}

And all of my custom form controls extend this base class. It's all good until here.

In one of the form controls, I needed to replace the original writeValue method. The problem is that the new writeValue method is not called but the writeValue method in the base class gets called.

export class CustomFormControl extends BaseControlValueAccessor<string> {
    constructor(
        @Self() @Optional() private ngControl: NgControl
    ) {
        super(ngControl);
    }

    writeValue(value: string) {
        this.value = value;
        console.log(value); // <- This is not called but the above log is called.
    }
}

Did anyone face this issue before? Actually, it seems more related to class inheritance than angular form control, however, I think I've implemented this correctly. Hope to get any help from you.

question from:https://stackoverflow.com/questions/65895411/writevalue-not-called-angular-custom-form-control

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...