Angular ng select required option

☆樱花仙子☆ 提交于 2019-12-11 01:13:40

问题


I cannot find out how to use the required option in ng-select.

I have tried this:

<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>

but no luck there..

Any ideas?


回答1:


You have to check on the value of registerUserData.skills if it is filled than show your Skills are required else, hide it.

That is to say:

<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>

NOTE:

  • I do not know what f.submitted and skills.invalid are, but assuming that they're related to the submit button event.

  • You can achieve a better result using ReactiveForms.



来源:https://stackoverflow.com/questions/53432744/angular-ng-select-required-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!