Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-select with form control required validation angular 7

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

like image 664
Cherry R Avatar asked Oct 26 '19 12:10

Cherry R


2 Answers

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.

like image 196
Fateme Fazli Avatar answered Oct 20 '22 05:10

Fateme Fazli


Add formControlName="prodCode"

<ng-select [items]="productData" [searchable]="true" bindLabel="productName" [formControlName]="prodCode" [ngClass]="{ 'is-invalid': submitted && f.prodCode.errors }"
  placeholder="Select Product" required>
</ng-select>
like image 21
Adrita Sharma Avatar answered Oct 20 '22 05:10

Adrita Sharma