1

我正在尝试将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);
    }
}

我收到以下错误: 在此处输入图像描述

我正在尝试这样做,以便我可以在附加了 formControlName 的表单中使用 EditorWrapperComponent,但无法弄清楚如何解决这个问题。如果这不是在表单中使用 ngx-monaco-editor 的正确方法,我愿意接受建议。

4

1 回答 1

1

我想我想通了。似乎所有需要做的就是

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

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

于 2020-08-16T15:39:03.320 回答