4

我不知道如何在 ng-select 中使用所需的选项。

我试过这个:

<ng-select
    #skills
    required
    [ngClass]="{ 'is-invalid': f.submitted && skills.invalid }" 
    [items]="options" 
    bindLabel="label" bindValue="value"
    [multiple]="true" placeholder="Select Skills" 
    [(ngModel)]="registerUserData.skills"                                       
    name="skills[]">
</ng-select>
<div *ngIf="f.submitted && skills.invalid" class="invalid-feedback">
    <div *ngIf="skills.errors.required">
       Skills are required
    </div>
</div>

但那里没有运气..

4

3 回答 3

4

没有内置required attributeng-select。我总是通过form验证来验证它。
在 angular2 或更高版本中,您可以将ng-selectwithngNativeValidate指令用于模板驱动的表单。

<form #registerUser="ngForm" ngNativeValidate (ngSubmit)="onSubmit()">  

   <ng-select
    class="col-md-8 required"
    [items]="options" 
    bindLabel="label" 
    bindValue="value"
    [multiple]="true" 
    name="skills"
    placeholder="Select Skills" 
    [(ngModel)]="registerUserData.skills"                                       
    required>
</ng-select>
<div *ngIf="!registerUserData.skills" class="invalid-feedback">
    Skills are required
</div>

<button type='submit' [disabled]="!registerUser.valid" [isFormValid]="!registerUser.valid">Submit</button>

</form>

当或和时,我也使用自定义style红色标记字段。您可以将其放在全局或文件中以与 all 一样工作。untouchedtouchedinvalidscsscsscomponent

SCSS:

ng-select.required.ng-invalid.ng-touched {
    .ng-select-container{
        border-color: #dc3545;
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
    }
}
ng-select.required.ng-invalid.ng-untouched {
    .ng-select-container{
        border-color: #dc3545;
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
    }
}

CSS:

ng-select.required.ng-invalid.ng-touched .ng-select-container{
 
    border-color: #dc3545;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
}
ng-select.required.ng-invalid.ng-untouched .ng-select-container {

    border-color: #dc3545;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
}
于 2020-07-26T07:42:55.997 回答
1

此外,当您使用@Majedur Ra​​haman 的答案时,请记住在输入上设置name属性。ng-select

这花了我几个小时。

于 2020-12-02T06:06:57.847 回答
0

您必须检查registerUserData.skills是否已填充的值,而不是显示您的Skills are required其他值,隐藏它。

也就是说:

<ng-select
    #skills
    [ngClass]="{ 'is-invalid': f.submitted && skills.invalid }" 
    [items]="options" 
    bindLabel="label" bindValue="value"
    [multiple]="true" placeholder="Select Skills" 
    [(ngModel)]="registerUserData.skills"                                       
    >
</ng-select>
    <div *ngIf="f.submitted && skills.invalid && !registerUserData.skills">
       Skills are required
    </div>

笔记:

  • 我不知道f.submittedskills.invalid是什么,但假设它们与提交按钮事件有关

  • 您可以使用ReactiveForms.

于 2018-11-22T14:20:14.980 回答