ng-select with form control required validation angular 7

Cherry R picture Cherry R · Oct 26, 2019 · Viewed 8.2k times · Source

I'm using ng-select for dropdown search but I'm unable to get validation if not selecting anything from dropdown. I return like bellow:

<div class="form-group">
   <ng-select [items]="productData" [searchable]="true" bindLabel="productName"
   [formControl]="prodCode"
   [ngClass]="{ 'is-invalid': submitted && f.prodCode.errors }"
   placeholder="Select Product" required>  
   </ng-select>
   <div *ngIf="submitted && f.prodCode.errors" class="invalid-feedback">
      <div *ngIf="f.prodCode.errors.required">Product Code is required</div>
   </div>
</div>

in Ts File

this.productForm = this.fb.group({
    prodCode: new FormControl(null, Validators.required)
});
get f() {
    return this.productForm.controls;
}
this.submitted = true;
if (this.productForm.invalid) {
    return;
}

So kindly requesting you please let me know where is my mistake....

Answer

Fateme Fazli picture Fateme Fazli · Oct 26, 2019

You can write it this way:

html:

<form [formGroup]="productForm" (submit)="submit()">
  <ng-select [items]="productData"
      [searchable]="true" 
      bindLabel="name"
      formControlName="prodCode">
  </ng-select>
  <span *ngIf="!productForm.get('prodCode').valid && productForm.get('prodCode').touched">
    <span *ngIf = "productForm.get('prodCode').errors['required']">is required</span>
  </span>
  <button class="btn btn-primary" type="submit">Submit</button> 
</form>

<pre>{{productForm.value|json}}</pre>

ts:

product: FormGroup;

constructor( ) { }

ngOnInit() { 
    this.productForm = new FormGroup({
    prodCode: new FormControl(null, Validators.required),
    });
}
submit(){
    this.validateAllFormFields(this.productForm);
    console.log(this.productForm.valid);
}

form validation on submit:

validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            const control = formGroup.get(field);
            if (control instanceof FormControl) {
                control.markAsTouched({onlySelf: true});
            } else if (control instanceof FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }

check Demo.