Two way data binding for object between components

时间:2016-06-30 12:44:40

标签: angular angular2-components

I have component with input:

<my-input *ngIf='filter.type === checkType.INPUT_TEXT' [filter]='filter'></my-input>

export class MyInputComponent{
  @Input() filter: any;
}

Template of MyInputComponent

<input name="name" [(ngModel)]="filter.input">

I want to set filter input inside and have influence on outer Component object.

How to pass filter object into MyInputComponent to achieve 2 way data binding?

I want to achIeve something like [(ngModel)]="filter.value" but working between Components

Other posts here about 2-way data binding does'nt answer my questions.

Edit:

After using extends DefaultValueAccessor in my MyInputComponent my parent component input disapears without any error.

import { Component, Input, OnInit, Provider, forwardRef } from '@angular/core';
import { FORM_DIRECTIVES, NG_VALUE_ACCESSOR, DefaultValueAccessor } from '@angular/common';

@Component({
  moduleId: module.id,
  selector: 'my-input',
  directives: [FORM_DIRECTIVES],
  host: { '(keyup)': 'doOnChange($event.target)' },
  templateUrl: '<input name="name" [(ngModel)]="filter.input">'
})

export class MyInputComponent extends DefaultValueAccessor {
  @Input() filter: any;

  onChange = (_) => {};
  onTouched = () => {};

  writeValue(filter:any):void {
    if (filter !== null) {
      super.writeValue(filter.toString());
    }
  }
  doOnChange(filter) {
    this.onChange(filter);
  }
}

const MY_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => MyInputComponent), multi: true});

1 个答案:

答案 0 :(得分:2)

您需要为此实现自定义值访问器。以下是此示例:

const MY_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => MyInputComponent), multi: true});

@Component({
  (...)
  providers: [ MY_VALUE_ACCESSOR ]
})
export class MyInputComponent extends DefaultValueAccessor {
  onChange = (_) => {};
  onTouched = () => {};

  writeValue(value:any):void {
    if (value!=null) {
      super.writeValue(value.toString());
    }
  }

  // call when your internal input is updated
  doOnChange(val) {
    this.onChange(val);
  }
}

有关详细信息,请参阅此文章(&#34;与NgModel兼容的组件&#34;部分):

另见这个问题: