1
votes

I am developing an Angular custom form component which should work on parts of an entire object model, while other standard form components work on other parts of the same model.

To do this, I have implemented ControlValueAccessor using this Thoughtram blogpost as a model.

For some reason, writeValue() for this component is not being called when another component in the same form mutates the model although for some reason, standard controls inside the component are updating.

This stackblitz example based on the Thoughtram post, illustrates the problem:

CounterInput1Component receives outerModel.integer as its ngModel, and operates on that.

CounterInput2Component receives the entire outerModel, then operates on the integer property.

When the integer is incremented, either via the standard input control or Counter2, writeValue() is called for Counter1.

However for Counter2, writeValue() is called (twice) on instantiation but never thereafter, whether incrementing from Counter1 or from the standard input control.

Why isn't writeValue() being called for Counter2? And how is it that in spite of this, its internal components are being told to update?

1

1 Answers

1
votes

It's not problem of your custom control form, remember that an object not change when you change a propertie of the object. You need change all the object

e.g. your input like

<input name="standardInput" 
     [ngModel]="outerModel.integer" 
     (ngModelChange)="outerModel={integer:$value}" />

Or a button

<button (click)="outerModel={integer:20}">click</button>

Aclaration: writeValue only happens when change the "object", and this happens in any control. see an example using a formControl in stackblitz

It's a simple formControl,

  form=new FormControl(this.data)
  ngOnInit()
  {
    this.form.valueChanges.subscribe(res=>{
      this.counter++
      console.log(res)
    })
  }
  click()
  {
   this.data.integer++
  }
    change()
  {
   this.data.integer++
   this.form.setValue(this.data);
  }

<pre>
{{form.value |json}}
Counter changes:{{counter}}
</pre>
<button (click)="click()">click</button>
<button (click)="change()">change</button>

We can not take account because the object is the same outside and inside the component, so the propertie change and you can see the real value, but repeat, there're not change