angular - 如何使用 angular2 设置验证器不接受索引 0 的选定选项

标签 angular typescript

我使用这样的选择选项

<div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success': (form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched)}">
      <label class="col-sm-3 control-label">blockFirstIndex</label>
      <div class="col-sm-9">
            <select formControlName="blockFirstIndex" [(ngModel)]="value" class="form-control">
                 <option *ngFor="let item of items" [disabled]="item.id==0" [ngValue]="item">{{item.name}}</option>
            </select>
      </div>
</div>

我的验证器

this.form = this.fb.group({
    'blockFirstIndex': ['', Validators.compose([Validators.required])],
});

如何让验证器不接受索引 0 的选择选项?

最佳答案

Form controller could be like this:

blockFirstIndex: new FormControl("", [
                    SelectionValidator.isValidSelection,
                    Validators.required
                ])

and you can define vlaidator like this:

import {FormControl} from '@angular/forms'; 
    export class SelectionValidator {
       static  isValidSelection(control: FormControl){
            if (control.value === "" || control.value=== "0") {
                return { "Please provide a valid selection": true };
            }
            return null;
        }

    }

关于angular - 如何使用 angular2 设置验证器不接受索引 0 的选定选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711090/

相关文章:

javascript - 如何使用 TypeScript/Angular 自定义我的 XLSX?

internationalization - 此时 Angular2 i18n?

javascript - 为什么 Angular 加载我的根模板两次

typescript - document.getElementById ("id") 可能为空

javascript - getByTestID 不适用于自定义组件

typescript - 当页面发生变化时,什么可以触发加载所有商店状态?

javascript - 导出的函数在 TypeScript 的 if 语句中不起作用

angular - 用于源映射扁平化的警告 : Unable to fully load/node_modules/ag-grid-angular/main. js

angular - 如果用户未登录 Angular2 2.0.0-rc.4,则重定向到登录路由

javascript - 修改后仍保留原始值