簡體   English   中英

Angular 2:向ngModelGroup添加驗證器

[英]Angular 2: Add validators to ngModelGroup

我正在使用ngModelGroup指令將多個表單輸入組合在一起。

在文檔( https://angular.io/docs/ts/latest/api/forms/index/NgModelGroup-directive.html )中,我讀到有一個validators: any[]屬性。

這是否意味着我可以添加一個自定義驗證器函數,該函數僅驗證該ngModelGroup 如果是這樣,我該如何使用它?

這將是非常棒的,因為我想檢查是否至少檢查了ngModelGroup中的一個復選框。 我無法使用required因為這意味着所有復選框都是必需的。 我在文檔中找不到任何相關內容,或者我找錯了地方?

這完全可以使用ngModelGroup和用於驗證的自定義指令。 了解其工作原理的關鍵是ngModelGroup

創建FormGroup實例並將其綁定到DOM元素。

首先,我們將構建我們的指令,這個指令非常簡單,沒有什么特別的東西:

@Directive({
  selector: '[hasRequiredCheckboxInGroup]',
  providers: [{provide: NG_VALIDATORS, useExisting: HasRequiredCheckBoxInGroup, multi: true}]
})
export class HasRequiredCheckBoxInGroup implements Validator, OnChanges {
  private valFn = Validators.nullValidator;

  constructor() {
    this.valFn = validateRequiredCheckboxInGroup();
  }

  validate(control: AbstractControl): {[key: string]: any} {
    return this.valFn(control);
  }
}

我們的驗證功能是我們掌握ngModelGroup創建FormGroup並應用它的關鍵知識的FormGroup

function validateRequiredCheckboxInGroup() : ValidatorFn {
      return (group) => { //take the group we declare in the template as a parameter
        let isValid = false; //default to invalid for this case
        if(group) {
          for(let ctrl in group.controls) {
            if(group.controls[ctrl].value && typeof group.controls[ctrl].value === 'boolean') { // including a radio button set might blow this up, but hey, let's be careful with the directives
              isValid = group.controls[ctrl].value;
            }
          }
        }

        if(isValid) {
          return null;
        } else {
          return { checkboxRequired: true };
        }
      }
    }

最后,在我們的模塊中包含並聲明了指令,我們返回到模板(需要在一個表單中):

<form #f="ngForm">
      <div ngModelGroup="checkboxes" #chks="ngModelGroup" hasRequiredCheckboxInGroup>
          <input type="checkbox" name="chk1" [(ngModel)]="checks['1']"/>
          <input type="checkbox" name="chk2" [(ngModel)]="checks['2']"/>
      </div>
      <div>
      {{chks.valid}}
      </div>
</form>

這里有一個可以玩的所有東西:... http://plnkr.co/edit/AXWGn5XwRo60fkqGBU3V?p=preview

謝謝大家幫幫我! 我接受了Silentsod的回答,因為它最有幫助。

我的最終解決方案是使用FormBuilder構建表單。

在我的組件中,創建表單並向其添加驗證器函數:

ngOnInit(): void {
    // Validator function:
    let validateMemberList = (group: FormGroup) => {
        let checked = Object.keys(group.controls).reduce((count, key: string) => {
            return count + (group.controls[key].value ? 1 : 0);
        }, 0);

        return checked === 0 ? {'minchecked': 1} : null;
    };

    this.jobForm = this.formBuilder.group({
        jobTitle: ['', Validators.required],
        // more inputs...
        members: this.formBuilder.group({}, {
            // The 2nd argument is an object with a validator property:
            validator: validateMemberList
        }),
        supportMembers: this.formBuilder.group({}, {
            validator: validateMemberList
        })
    });

然后在我的模板中:

<form [formGroup]="jobForm">
    <ul formGroupName="members">
        <li *ngFor="let user of teamMembers.members">
            <label class="e-label">
                <input class="e-input" type="checkbox" [formControlName]="user.$key">
                <user-badge [user]="user"></user-badge>
            </label>
        </li>
    </ul>
...

這會驗證表單,允許我顯示錯誤並禁用提交按鈕。

謝謝大家的幫助!

看起來ModelGroup中的每個控件都應該有自己的驗證器。 完成此操作后,您可以通過驗證器數組訪問每個。 所以將必需的屬性添加到所需的輸入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM