提问者:小点点

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


我有一个共同的组成部分,持有ngx羽毛的组成部分。我想调用其他几个组件来获取编辑器,而不是输入字段。我成功地做到了这一点。但是我正在使用ngModels进行双向数据绑定,这不能在Div上使用。我如何在我的公共组件中访问它们。

这是我的共同点:

common_component.html

<quill-editor>
</quill-editor>

公共_组件。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,我不能把它手动,因为这将被用作公共组件。

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

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


共1个答案

匿名用户

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

假设您在quill编辑器上绑定了value变量:

<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
  }
}

现在,您可以使用双向数据绑定在该命令QuillComponent上:

<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/