Two-way data binding for an object between components

I have a component with input:

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

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

MyInputComponent Template

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

I want to set the filter input internally and affect the external Component object.

How to pass a filter object in MyInputComponentto achieve two-way data binding?

I need something like [(ngModel)] = "filter.value", but work between components

Other posts here about linking two-way data do not answer my questions.

Edit:

After using extends DefaultValueAccessorin my MyInputComponent, my original component input disappears without any errors.

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});
+4
source share
1 answer

. :

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

. ( ", NgModel" ):

:

+2

All Articles