phil123456
phil123456

Reputation: 207

Angular 2 - ControlValueAccessor - (ngModelChange) not triggered

[edit: this code is actually working, so it may serve as a simple example on how to implement ControlValueAccessor for beginners]

I made a custom component, of the simplest form, a simple dif, that changes its internal state when clicking on it

problem : the ngmodel (someValue) is updated but the function doLiveChange() never gets triggered

<my-on-off [(ngModel)]="someValue" (ngModelChange)="doLiveChange()" > 
</my-on-off>

I am also not sure what is required or not in my component... every body is doing it his own way, overcomplicating examples while it should be just a simple interface

@Component({
    selector: 'my-on-off',
    templateUrl: './onOff.component.html',
    styleUrls: ['./onOff.component.css'],
    providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => OnOffComponent),
      multi: true
    }
  ]
})

export class OnOffComponent implements OnInit,ControlValueAccessor {

    onChange;

    /* this component implements it's own ngModel lifecycle */
    @Input('active') active:number=null; // this is mapped to [(ngModel)] value, see below

    constructor() {
    }

    ngOnInit() {
    }

    onClick(event)
    {
        this.active=1-this.active;
        this.onChange(this.active);
    }

    //-------------------------- interface

    // when model -> view changes are requested.
    writeValue( value : any ) : void {
        if(value!=="")
        {
            this.active=value;
        }
        else
            this.active=null;
    }

    // callback function that should be called when the control's value changes in the UI
    registerOnChange( fn : any ) : void {
        this.onChange = fn;
    }
    setDisabledState( _isDisabled : boolean ) : void {
    }

    // callback function that should be called when the control's value changes in the UI (blur event)
    registerOnTouched(_fn: any):void
    {

    }
}

the template :

<div class="onOffMainDiv" (click)="onClick($event)" [ngClass]="{'active':active==1}" title="ON/OFF"></div>

tell me if you need more infos

thanks

Upvotes: 1

Views: 1980

Answers (1)

phil123456
phil123456

Reputation: 207

was'nt working yesterday, jut came to work this morning, and it worked while I was demonstrating the issue to a colleague

maybe the inner state of the compiler was messed and restarting the project did the trick

hate when these happen

Upvotes: 1

Related Questions