How to trigger change() in a angular form by a custom control without an input

心不动则不痛 提交于 2021-02-07 13:58:41

问题


I do want to create a custom control which does not include any input. Whenever the control changes, I do want to save the complete form.

Our current approach uses the form-changed-event like this:

 <form #demoForm="ngForm" (change)="onChange()">
      <custom-input name="someValue" [(ngModel)]="dataModel">
      </custom-input>
 </form>

As you can see, we use the "change"-event to react to any change in the form. This works fine as long as we have inputs, checkboxes, ... as controls.

But our custom control does only exist out of a simple div we can click on. Whenever I click on the div the value of the control is increased by 1. But the "change"-event of the form is not fired. Do I somehow have to link my custom control to the form? Or are there any events which need to be fired?

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
    selector: 'custom-input',
    template: `<div (click)="update()">Click</div>`,
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => CustomInputComponent),
        multi: true
    }]
})
export class CustomInputComponent implements ControlValueAccessor {

    private onTouchedCallback: () => void = () => {};
    private onChangeCallback: (_: any) => void = () => {};

    update(){
      this.value++;
    }

    get value(): any {
        return this.innerValue;
    };

    set value(v: any) {
        console.log("Change to");
        if (v !== this.innerValue) {
            this.innerValue = v;
            this.onChangeCallback(v);
        }
    }

    writeValue(value: any) {
        if (value !== this.innerValue) {
            this.innerValue = value;
        }
    }

    registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }

    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }
}

I've created a plunker to demonstrate the problem: https://plnkr.co/edit/ushMfJfcmIlfP2U1EW6A

Whenever you click on "Click" the model-value is increased, but there is no output on the console, as the change-event is not fired... (There is a console.log linked to the change-event)


回答1:


Thanks for your replies.

Finally I found the following solution to this problem: As Claies mentioned in the comment, my custom component does not fire the change event. Therfore the form does never know about the change. This has nothing todo with angular, but as said is the expected behaviour of a input/form.

The easiest solution is to fire the change-event in the customcontrol when a change happens:

constructor(private element: ElementRef, private renderer: Renderer) {
}

public triggerChanged(){
    let event = new CustomEvent('change', {bubbles: true});
    this.renderer.invokeElementMethod(this.element.nativeElement, 'dispatchEvent', [event]);
}

That's it, whenever I called "onControlChange(..)" in my custom component, then I fire this event afterward.

Be aware, that you need the Custom-Event-Polyfill to support IE! https://www.npmjs.com/package/custom-event-polyfill




回答2:


Thanks Stefan for pointing me in the right direction.

Unfortuantely Renderer (which has invokeElementMethod()) has recently been deprecated in favor or Renderer2 (which does not have that method)

So the following worked for me

this.elementRef.nativeElement.dispatchEvent(new CustomEvent('change', { bubbles: true }));



回答3:


You need to emit the click event of div to its parent. so that you can handle the event.

Plunker Link

Parent component:

import { Component, forwardRef, Output, EventEmitter } from '@angular/core'; // add output and eventEmitter
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
 selector: 'custom-input',
 template: `<div (click)="update($event)">Click</div>`,
 providers: [{
 provide: NG_VALUE_ACCESSOR,
 useExisting: forwardRef(() => CustomInputComponent),
 multi: true
}]
})

export class CustomInputComponent implements ControlValueAccessor {

  private onTouchedCallback: () => void = () => {};
  private onChangeCallback: (_: any) => void = () => {};
  @Output() clickEvent = new EventEmitter(); // add this

  update(event){
    this.value++;
    this.clickEvent.emit(event); // emit the event on click event
  }

  get value(): any {
      return this.innerValue;
  };
}

child component:

//our root app component
import {Component} from '@angular/core'

@Component({
    selector: 'demo-app',
    template: `
        <p><span class="boldspan">Model data:</span> {{dataModel}}</p>
        <form #demoForm="ngForm">
          <custom-input name="someValue" 
                      [(ngModel)]="dataModel" (clickEvent) = onChange()> // handling emitted event here
            Write in this wrapper control:
          </custom-input>
        </form>`
})
export class AppComponent {
    dataModel: string = '';

    public onChange(){
      console.log("onChangeCalled");
    }
}



回答4:


It seems that change event is not fired on form when you call ControlValueAccessor onChange callback (callback passed in registerOnChange function), but valueChanges observable (on the whole form) is triggered.

Instead of:

 ...
 <form (change)="onChange()">
 ...

you can try to use:

this.form.valueChanges
  .subscribe((formValues) => {
    ...
  });

Of course, you must get proper form reference in your component.



来源:https://stackoverflow.com/questions/42372110/how-to-trigger-change-in-a-angular-form-by-a-custom-control-without-an-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!