如何将ngx-monaco-editor包装在ControlValueAccessor组件中

问题描述

我试图将ngx-monaco-editor github用于简单的faas应用程序,并试图使其在FormGroup中使用。

这是我的组件的样子:

@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);
    }
}

并且我收到以下错误

enter image description here

我正在尝试执行此操作,以便可以在附加了formControlName的表单中使用EditorWrapperComponent,但无法找出解决方法。如果这不是在表单中使用ngx-monaco-editor的正确方法,那么我会提出建议。

解决方法

我想我明白了。似乎所需要做的就是

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

this.onChange和this.onTouched是我存储ControlValueAccessor提供的onTouched和onChange函数的变量。