如何从另一个组件访问[ngModel]?

问题描述

我有一个包含ngx-quill组件的通用组件。我想调用其他几个组件来获取编辑器而不是输入字段。我成功完成了这项工作。但是我正在使用ngModels进行双向数据绑定,这不能在Div上使用。如何在我的通用组件中访问它们。

所以这是我的常用组件:

common_component.html

<quill-editor>
</quill-editor>

Common_component.ts:

import { Component } from '@angular/core';
import * as _ from 'underscore';

@Component({
    selector: 'app-quill-editor',templateUrl: './common_component.html'
})

export class CommanquillComponent {

    constructor(
    ) {}

}

这就是我所说的:

main_component.html

<div>
    <app-quill-editor
        id="float-input"
        placeholder=" "
        name="myRange"
        step="1"
        [(ngModel)]="myVar"
    ></app-quill-editor>
</div>

main_component.ts除了变量声明外什么都没有。

在这里的问题是ngModel不能在div上使用(它会抛出错误),html认为是div标签,然后在其中调用,我希望将ngModel放在上,因此无法手动放置用作通用组件。

请帮助我了解如何实现此数据绑定?

感谢您的支持,并让我知道是否应在帖子中添加更多易于理解的代码

解决方法

您需要寻找ControlValueAccessor来实现自定义表单控件,以便双向数据绑定可以在自定义组件上工作。

假设您在value上绑定了quill-editor变量:

<quill-editor [ngModel]="value" (ngModelChange)="onChange($event)"></quill-editor>
@Component({
  ...
  providers: [
    { 
      provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() => CommanQuillComponent),multi: true
    }
  ]
})
export class CommanQuillComponent implements ControlValueAccessor() {
   value: string = '';

   ...
   // Add other properties as Input
   @Input()
   placeholder: string;

   ...

   propagateChange = (_: any) => {};
   registerOnChange(fn) {
    this.propagateChange = fn;
  }
  
  writeValue(value: string) {
     this.value = value; // <- you receive the value which is binded to this component here
  }

  onChange(event: string) {
     this.value = event;
     this.propagateChange(event); // <- you export the value so the binded variable is updated
  }
}

现在您可以在该CommanQuillComponent上使用双向数据绑定:

<div>
    <app-quill-editor
        id="float-input"
        placeholder=" "
        name="myRange"
        step="1"
        [(ngModel)]="myVar"
    ></app-quill-editor>
</div>

您可以阅读许多在线文章以获得更多详细信息:

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

https://javascript-conference.com/blog/angular-reactive-forms-building-custom-form-controls/

https://codinglatte.com/posts/angular/angular-build-custom-form-control/