Home > Net >  Select dropdown send null when submit the form(Angular, Reactive Form)
Select dropdown send null when submit the form(Angular, Reactive Form)

Time:11-20

When I try to submit a reactive form, select send null, instead of the value from dropdown. I use Angular 12. I tried also with [ngValue] for the option tag, and it's the same. I attached the html, the typescript component and the module. I used reactive forms for that, I imported that module in the module for that component. I will appreciate any help. Thank you!

TYPESCRIPT COMPONENT

import { Component, OnInit } from '@angular/core';
  import { FormBuilder, FormGroup } from '@angular/forms';
  
  @Component({
  selector: 'app-post-a-job',
  templateUrl: './post-a-job.component.html',
  styleUrls: ['./post-a-job.component.scss']
})
export class PostAJobComponent implements OnInit {
  
  myForm: FormGroup;
 
 jobTypes = [{
    value: 'manager', view: 'Manager'
  }]
 
 constructor(private fb: FormBuilder) { }
 
 ngOnInit(): void {
    this.buildForm();
  }

  buildForm() {
    return this.myForm = this.fb.group({
      jobType: null
    });
  }
 save(form) {
    console.log(JSON.stringify(form.value));
  }
   }
MODULE

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { JobsRoutingModule } from './jobs-routing.module';
import { JobsComponent } from './jobs.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { PostAJobComponent } from './components/post-a-job/post-a-job.component';


@NgModule({
  declarations: [
    JobsComponent,
    PostAJobComponent
  ],
  imports: [
    CommonModule,
    JobsRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ]
})
export class JobsModule { }
HTML

<form [formGroup]="myForm">
 <select formControlName="jobType">
            <option [value]="null">(new customer)</option>
            <option [value]="job.value" *ngFor="let job of jobTypes">
                {{job.view}}
            </option>
</select>
 <button type="submit" (click)="save(myForm)" class="btn btn-default">Submit</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Just copied your code into the project, there is no problem, I wonder what your problem is

I found two verification problems

  myForm!: FormGroup;

  save(form:any) {
    console.log(JSON.stringify(form.value));
  }
```

CodePudding user response:

Even though I dont see anything wrong from your code, but you can try prevent the error by disable the placeholder, like :

<option [value]="null" disabled>(new customer)</option>

And validate your submit process :

save(form) {
  let val = form.value
  if(!val.jobType)return
}

CodePudding user response:

The problem was because it was installed a package jquery-nice-select on my project. Thank you all!

  • Related