Angular 2-ControlValueAccessor-(ngModelChange)未触发

时间:2018-09-18 13:07:59

标签: angular custom-controls ngmodel angular-ngmodelchange

[编辑:此代码实际上正在工作,因此它可以作为有关如何为初学者实现ControlValueAccessor的简单示例]

我制作了一个自定义组件,其形式最简单,即简单的dif,可在单击该组件时更改其内部状态

问题:ngmodel(someValue)已更新,但函数doLiveChange()从未触发

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

我也不知道组件中需要什么... 每个人都按自己的方式操作,使示例复杂化,而它只是一个简单的界面

@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
    {

    }
}

模板:

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

告诉我是否需要更多信息

谢谢

1 个答案:

答案 0 :(得分:0)

昨天不工作,今天早上突出来上班,而当我向同事演示这个问题时,它起作用了

也许是编译器的内部状态混乱了,然后重新启动项目就成功了

在发生这种情况时讨厌

相关问题