【问题标题】:How do I wrap ngx-monaco-editor in a ControlValueAccessor component如何将 ngx-monaco-editor 包装在 ControlValueAccessor 组件中
【发布时间】:2020-12-05 18:00:16
【问题描述】:

我正在尝试将 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 的正确方式,我愿意接受建议。

【问题讨论】:

  • 你需要 this.editorComponent.writeValue 调用吗?我希望设置 this.value 就足够了。问题是 this.editorComponent 在调用 writeValue 时不存在
  • @MikeOne 好吧,是的,删除这些调用确实消除了异常。当我以编程方式更改它时,我确实在编辑器中看到了该值,例如new FormControl('placeholder') 但如果我要在浏览器中更改它,那么我看不到 formcontrol.value 的新值。

标签: angular controlvalueaccessor ngx-monaco-editor


【解决方案1】:

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

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

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

【讨论】:

  • 您能否发布整个组件的工作示例?
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-20
相关资源
最近更新 更多