angular 自定义表单/*ngFor增删不更新

自定义表单项目实践

<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]
posted @ 2021-07-16 17:29  猫神甜辣酱  阅读(120)  评论(0编辑  收藏  举报