自定义组件的基本结构
import { Component, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'sg-photo-view',
templateUrl: 'photo-view.component.html',
providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => PhotoViewComponent), multi: true, }],
})
export class PhotoViewComponent implements OnInit, ControlValueAccessor {
private propagateChange = (_: any) => { };
imgs: string[];
constructor(
) { }
ngOnInit() {
}
/**
* 给外部formControl写入数据
*
* @param {*} value
*/
writeValue(value: any) {
if (value != undefined) {
if (value instanceof Array) {
this.imgs = value;
} else {
this.imgs = [value];
}
}
}
/**
* 把外面登记的监测change的函数赋值给this.propagateChange
* 当内部数据改变时,可使用this.propagateChange(this.imgs)去触发传递出去
* @param {*} fn
*/
registerOnChange(fn: any) {
this.propagateChange = fn;
}
/**
* 也是一样注册,当 touched 然后调用
* @param {*} fn
*/
registerOnTouched(fn:any) { }
/**
* 内部更改例子
* @param {*} fn
*/
inSideChange(){
this.imgs.push(1);
this.propagateChange(this.imgs)//去触发外部监控的函数
}
}
使用
<sg-photo-view formControlName="binding"
></sg-photo-view> //响应式表单
<sg-photo-view [(ngModel)]="binding" name = "some"
></sg-photo-view> // 模板驱动表单
参考
网友评论