在作为组件的反应形式控件上使用验证

时间:2018-12-15 13:45:37

标签: angular

如何在FormBuilder中对该组件运行自定义验证?

例如,当用户从下拉列表onClickItem(item)中选择一项时 如何在主表单组件中对选定的item运行验证功能?

主要表单组件中的FormBuilder:

this.itemForm = this.fb.group({
   name: ['', [Validators.required, Validators.minLength(3)]],
   description: ['', [Validators.required, Validators.minLength(10)]],
   itemName: [] // run validation on this component
});

然后我可以在itemName上使用验证器,例如:itemName: [, MyValidator.itemNotUsed],

模板:

<app-dropdown-select formControlName="itemName"
     [dropdownItems]="items">
</app-dropdown-select>

下拉选择组件:

@Component({
  selector: 'app-dropdown-select',
  templateUrl: './dropdown-select.component.html',
  styleUrls: ['./dropdown-select.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DropdownSelectComponent),
      multi: true
    }
  ]
})
export class DropdownSelectComponent implements ControlValueAccessor {

  @Input() combinedInput: boolean;
  @Input() dropdownItems: DropdownItem[];
  _selectedItem: DropdownItem;
  showList: boolean;
  buttonIcon: string;

  propagateChange = (_: any) => {};

  set selectedItem(value) {
    this._selectedItem = value;
    this.propagateChange(this._selectedItem);
  }

  get selectedItem() {
    return this._selectedItem;
  }

  constructor(private el: ElementRef) { }

  OnInit() {
    this.buttonIcon = BUTTON_ICON_INACTIVE;
    this.selectedItem = this.dropdownItems[0];
    console.log(this.dropdownItems);
  }

  onClick() {
    this.toggleShowList();
  }

  toggleShowList() {
    this.showList = !this.showList;
    if (!this.showList) {
      this.buttonIcon = BUTTON_ICON_INACTIVE;
    } else {
      this.buttonIcon = BUTTON_ICON_ACTIVE;
    }
  }

  onClickItem(item) {
    this.showList = false;
    this.selectedItem = item;
    this.propagateChange(this.selectedItem);
  }

  writeValue(value: any) {
    if (value !== undefined) {
      this.selectedItem = value;
    }
  }

  registerOnChange(fn) {
    console.log('register change');
    this.propagateChange = fn;
  }

  registerOnTouched() {}

}

2 个答案:

答案 0 :(得分:0)

您需要添加为提供程序NG_VALIDATORS,请参见https://medium.com/@tarik.nzl/angular-2-custom-form-control-with-validation-json-input-2b4cf9bc2d73

因此,您的提供商就像

providers: [
{
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DropdownSelectComponent),
  multi: true,
},
{
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => DropdownSelectComponent),
  multi: true,
}

如果您在自己的组件中需要其他验证器(不需要),则可以实现Validator并创建类似Validate的功能

public validate(c: FormControl) {
    //implement your logic here
    let error:boolean
    return error?{
        customError:"ERROR"
    }:null;
}

答案 1 :(得分:0)

定义

@Output('itemSelected') itemSelected = new EventEmitter(); //in DropdownSelectComponent

然后,当您选择项目调用时

this.itemSelected.emit(item);

您可以像这样在主要组件中获取所选项目

<app-dropdown-select formControlName="itemName"
     [dropdownItems]="items" (itemSelected)="doValidation($event)">
</app-dropdown-select>