angularcontrolvalueaccessorngx-monaco-editor

How do I wrap ngx-monaco-editor in a ControlValueAccessor component


I am trying to use ngx-monaco-editor github for a simple faas application and am trying to enable it to be used within a FormGroup.

This is how my component looks like:

@Component({
    selector: 'app-editor-wrapper',
    template: `<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="value" ></ngx-monaco-editor>`,
    styleUrls: ['./editor-wrapper.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => EditorWrapperComponent),
            multi: true
        }
    ]
})
export class EditorWrapperComponent implements ControlValueAccessor, AfterViewInit {

    @ViewChild(EditorComponent) editorComponent: EditorComponent;

    editorOptions: any;
    value: string;
    disabled: boolean;

    constructor() { }

    ngAfterViewInit(): void {
        console.log(this.editorComponent);
    }

    //#region ControlValueAccessor
    writeValue(obj: any): void {
        this.value = obj;
       // this.editorComponent is undefined
        this.editorComponent.writeValue(obj);
    }
    onChange: () => {};
    registerOnChange(fn: any): void {
        this.onChange = fn;
       // this.editorComponent is undefined
        this.editorComponent.registerOnChange(fn);
    }
    onTouched: () => {};
    registerOnTouched(fn: any): void {
        this.onTouched = fn;
       // this.editorComponent is undefined
        this.editorComponent.registerOnTouched(fn);
    }
    setDisabledState?(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }
   //#endregion

   ngAfterViewInit(): void {
       // this works fine
        console.log(this.editorComponent);
    }
}

And I receive the following error: enter image description here

I am trying to do this so that I can use EditorWrapperComponent within a form with formControlName attached to it but cannot figure out how to fix this. If this is not the right way of using ngx-monaco-editor within a form I open to suggestions.


Solution

  • I think I figured it out. It seems that all that was needed to be done was

    ngAfterViewInit(): void {
        this.editorComponent.registerOnChange(this.onChange);
        this.editorComponent.registerOnTouched(this.onTouched);
    }
    

    this.onChange and this.onTouched are variables where I stored onTouched and onChange functions provided by the ControlValueAccessor.