[编辑:这段代码实际上是有效的,所以它可以作为一个简单的例子来说明如何为初学者实现 ControlValueAccessor]
我制作了一个最简单形式的自定义组件,一个简单的差异,当点击它时会改变它的内部状态
问题:更新了 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>
告诉我您是否需要更多信息
谢谢