首页 文章

如何访问自定义组件中的Validator.required

提问于
浏览
1

我需要一些帮助 . 我正在尝试创建一个包装下拉值的自定义组件,并根据是否需要显示/隐藏默认的--Select--选项 . (我想稍后将其他自定义逻辑应用于此组件)

如何通过父级的被动形式设置我的自定义控件中的Validator.required?

我是Angular的新手,但不是AngularJS

父页面html:

<div formGroupName="siteType">
    <my-dropdownlist 
        id="siteType"
        formControlName="code" 
        [items]="arrayOfItems">
    </my-dropdownlist>
</div>

父页面.ts:

export class MyPage {

serviceForm: FormGroup = this.fb.group({
    siteType: this.fb.group({
        code: [serviceData.siteType, Validators.required]  
    })
});

自定义控件html:

<select class="form-control" id="itemType">
    <option *ngIf="!selectedValue && required">--Select--</option>
    <option *ngFor="let item of items" [value]="item">
        {{ item }}
    </option>
</select>

定制控制ts:

import { Component, Input, Output, EventEmitter, forwardRef, OnInit} from '@angular/core';
import { NG_VALIDATORS, FormControl, Validator, NgForm, FormBuilder } from '@angular/forms';

@Component({
    selector: 'my-dropdownlist',
    templateUrl: './dropdownlist.component.html',
    providers: [
        {
            provide: NG_VALIDATORS,
            useExisting: forwardRef(() => DropdownListComponent),
            multi: true
        }
    ]
})
export class MyDropdownListComponent implements Validator, OnInit {
    @Input() items: any[];
    @Input() required: boolean = false;
    @Input() formControlName: string;
    private selectedValue: any;

    ngOnInit() {
        //Some way to get at the Validator.required set on the parent form here so I can tell whether to apply it to my dropdown?
    }
    public validate(c: FormControl) {
        return null;  //TODO for additional future validation
    }
}

1 回答

  • 0

    假设孩子应该是可重用性的通用组件 . 我要做的是传递嵌套的formcontrol而不是字符串 . 这样就可以获得表单控件及其中的所有验证器 . 同时,由于您正在获取对象,因此父级也将捕获对该字段所做的更改 . 所以通过控制:

    <my-dropdownlist 
      [ctrl]="serviceForm.controls.siteType.controls.code"
      [items]="arrayOfItems">
    </my-dropdownlist>
    

    然后当然更改 @Input

    @Input() items: any[];
    @Input() ctrl: FormControl;
    

    由于我可以在您的代码中看到您将来有验证,这意味着我们可以通过检查表单控件是否有效或使用 ctrl.errors.required 来有条件地显示 --Select-- 选项:

    <select class="form-control" id="itemType" [formControl]="ctrl">
      <option *ngIf="!ctrl.valid" [ngValue]="null">--Select--</option>
      <option *ngFor="let item of items" [value]="item">
        {{ item }}
      </option>
    </select>
    

    你也可以摆脱提供者的 NG_VALIDATORS :)

相关问题