自定义表单项目实践
父
<app-two [(ngModel)]="books"></app-two>
books=''
子
@Component({
selector: 'app-two',
templateUrl: './two.component.html',
styleUrls: ['./two.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TwoComponent),
multi: true,
}
]
})
export class TwoComponent implements ControlValueAccessor {
constructor() {
}
onChange: (value: any) => void = () => null;
onTouched: () => void = () => null;
_disabled = false;
// 父传子赋值
@Input()
set value(value: any) {
this.sex = value;
}
sex = ''
ngAfterViewInit() {
}
//父传子的时候赋值给子
writeValue(obj: any): void {
this.sex = obj;
}
//同步更新的事件
registerOnChange(fn: any): void {
this.onChange = fn;
}
//失去焦点的事件
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
// //父传子禁用的值
// setDisabledState(isDisabled: boolean): void {
// this._disabled = isDisabled
// }
}
<input type="text" [(ngModel)]="sex" (ngModelChange)="onChange($event)" >
*ngFor 增删不更新
push ,splice
this.arr=[...this.arr]