Angular 2如何在ControlValueAccessor内的控件上调用markAsDirty()

时间:2016-10-12 07:04:12

标签: angular

我有一个出生日期定制控制,有3个内部输入。 当所有3个输入都变脏时,我只希望将父控件标记为脏。

我需要从Custom值访问器中访问NgModel的控件,我该如何实现?代码不是必需的,但如下所示:

@Directive({
  selector: '[validateDateOfBirth][formControlName],[validateDateOfBirth][formControl],[validateDateOfBirth][ngModel]',
  providers: [
  { provide: NG_VALIDATORS, useExisting: forwardRef(() => DateOfBirthValidator), multi: true }
  ]
})
export class DateOfBirthValidator implements Validator {
  constructor(@Attribute('validateDateOfBirth') public validateDateOfBirth: string) {

  }
  validate(c: AbstractControl): { [key: string]: any } {
    let v: DateOfBirthVm  = c.value;
    let valid = false;
    if(v && v.month && v.year) {
      return null;
    }
    return {
      validateDateOfBirth: false
    }
  }
}
<date-of-birth
  validateDateOfBirth
  ngDefaultControl
  [(ngModel)]="model.dateOfBirth"
  #dateOfBirth="ngModel"
  name="dateOfBirth"></date-of-birth>
export class DateOfBirth implements ControlValueAccessor {

  @Input() name: string;

  private _viewModel: DateOfBirthVm = new DateOfBirthVm();

  private _yearOptions: Array<number> = [];
  private _monthInputValue: string = '';
  private _monthControl: FormControl = new FormControl();
  private _yearInputValue: string = '';
  private _yearControl: FormControl = new FormControl();

  constructor(private _appSettings: AppSettings) {
    this._monthControl.valueChanges.subscribe((value: string) => {
      this._viewModel.month = value;
    });
    this._yearControl.valueChanges.subscribe((value: string) => {
      this._viewModel.year = value;
    });
  }

  ngOnInit() {
    for(let i=(this._appSettings.currentYear-18); i>1909; i--) {
      this._yearOptions.push(i);
    }
  }

  //Interface specific stuff.
  //To notify external component's that the model has changed, we must call our
  //registeredOnChange handler. (e.g _onChanged()). Simply calling it, informs other components.
  registerOnChange(fn: any) { this._onChanged = fn; }
  registerOnTouched(fn: any) { this._onTouched = fn; }
  private _onChanged = (value) => { };
  private _onTouched = () => { };
  //write value is called when an external component writes to our model.
  //e.g if another component with ([ngModel])="myAutoCompleteValue", calls myAutoCompleteValue = '';
  writeValue(vm: DateOfBirthVm) {
    if(!vm) {
      this._viewModel.month = '';
      this._viewModel.year = '';
    } else {
      this._viewModel = vm;
      this._monthInputValue = vm.month;
      this._yearInputValue = vm.year;
      this._onChanged(vm);
    }
  }

}

1 个答案:

答案 0 :(得分:2)

当尚未改变所有内容时,请不要致电_onChanged()_onTouched()