如何在Angular中显示所选复选框时去掉 ‘逗号’。

huangapple go评论103阅读模式
英文:

How to remove 'commas' while displaying the selected checkboxes in angular

问题

你可以在处理 checkbox 值的时候,将空字符串('')过滤掉,以避免生成额外的逗号。你可以在 onSubmit 方法中修改 checkboxValues 的代码,如下所示:

  1. onSubmit() {
  2. if (this.form.valid) {
  3. // ...
  4. this.checkboxValues = this.checkboxesFormArray.value.filter(value => value !== ''); // Filter out empty strings
  5. this.form.controls['checkbox'].setValue(this.checkboxValues);
  6. this.carServiceService.addCar(this.form.value).subscribe(response => {
  7. // ...
  8. });
  9. } else {
  10. // Form is invalid, display error messages
  11. this.form.markAllAsTouched();
  12. }
  13. }

这样,checkboxValues 数组将只包含被选中的复选框的值,而不会有空字符串。这应该解决你在表格中得到额外逗号的问题。

英文:

form-page.component.html :

  1. <h1>CAR SERVICE FORM</h1>
  2. <form [formGroup]="form" (submit)="onSubmit()">
  3. <div>
  4. <label for="carmodel">Car Model:</label>
  5. <input type="text" class="form-control" formControlName="carmodel">
  6. <div *ngIf="form.controls['carmodel'].touched && form.controls['carmodel'].errors">
  7. <div *ngIf="form.controls['carmodel'].hasError('required')" class="error">Carmodel is required.</div>
  8. <div *ngIf="form.controls['carmodel'].hasError('minlength')">Carmodel should be minimum 3 characters.</div>
  9. </div>
  10. </div>
  11. <div>
  12. <label for="carnum">Car Number:</label>
  13. <input type="text" class="form-control" formControlName="carnum">
  14. <div *ngIf="form.controls['carnum'].touched && form.controls['carnum'].errors">
  15. <div *ngIf="form.controls['carnum'].hasError('required')" class="error">carnum is required.</div>
  16. </div>
  17. </div>
  18. <div>
  19. <label for="contactNumber">Contact Number:</label>
  20. <input type="text" class="form-control" formControlName="contactNumber">
  21. <div *ngIf="form.controls['contactNumber'].touched && form.controls['contactNumber'].errors">
  22. <div *ngIf="form.controls['contactNumber'].hasError('required')" class="error">Contact number is required.</div>
  23. </div>
  24. </div>
  25. <div>
  26. <label>Type of Service:</label>
  27. <div>
  28. <label><input type="radio" name="option" value="Waterwash" formControlName="option"> Waterwash </label>
  29. </div>
  30. <div>
  31. <label><input type="radio" name="option" value="Fullservice" formControlName="option"> Fullservice </label>
  32. </div>
  33. <div *ngIf="form.controls['option'].touched && form.controls['option'].invalid">
  34. <div class="error">Please select an option</div>
  35. </div>
  36. </div>
  37. <div>
  38. <label>Addons:</label>
  39. <div *ngFor="let cbx of checkboxesFormArray.controls; let i = index">
  40. <label formArrayName="checkbox">
  41. <input type="checkbox" [formControlName]="i" (change)="checkedChanged($event)" [value]="checkboxes[i].value">
  42. {{checkboxes[i].name}}
  43. </label>
  44. </div>
  45. </div>
  46. <div>
  47. <label>State:</label>
  48. <select formControlName="state" (change)="onStateChange()">
  49. <option *ngFor="let state of states" [value]="state">{{state}}</option>
  50. </select>
  51. <div *ngIf="form.controls['state'].touched && form.controls['state'].invalid">
  52. <div class="error">Please select a state</div>
  53. </div>
  54. </div>
  55. <div>
  56. <label>City:</label>
  57. <select formControlName="city">
  58. <option *ngFor="let city of cities[form.controls['state'].value]" [value]="city">{{city}}</option>
  59. </select>
  60. <div *ngIf="form.controls['city'].touched && form.controls['city'].invalid">
  61. <div class="error">Please select a city</div>
  62. </div>
  63. </div>
  64. <button type="submit" class="btn btn-primary">Submit</button>
  65. <button type="button" (click)="Reset()">Reset</button>
  66. <button (click)="goBack()">back</button>
  67. </form>
  68. <table>
  69. <thead>
  70. <tr>
  71. <th>Car Model</th>
  72. <th>Car Number</th>
  73. <th>Contact Number</th>
  74. <th>Type of Service</th>
  75. <th>Options</th>
  76. <th>State</th>
  77. <th>City</th>
  78. </tr>
  79. </thead>
  80. <tbody>
  81. <tr *ngFor="let car of cars">
  82. <td>{{ car.carmodel }}</td>
  83. <td>{{ car.carnum }}</td>
  84. <td>{{ car.contactNumber }}</td>
  85. <td>{{ car.option }}</td>
  86. <td>{{ car.checkbox }}</td>
  87. <td>{{ car.state }}</td>
  88. <td>{{ car.city }}</td>
  89. </tr>
  90. </tbody>
  91. </table>

form-page.component.ts :

  1. import { Component } from '@angular/core';
  2. import { CommonModule, Location } from '@angular/common';
  3. import { FormGroup, FormBuilder,FormControl, Validators, FormArray } from '@angular/forms';
  4. import { CarServiceService } from 'src/app/services/car-service.service';
  5. @Component({
  6. selector: 'app-form-page',
  7. templateUrl: './form-page.component.html',
  8. styleUrls: ['./form-page.component.css']
  9. })
  10. export class FormPageComponent {
  11. //
  12. form: FormGroup;
  13. states: string[] = ['Tamilnadu', 'Kerala', 'Karnataka','Maharastra'];
  14. cities: {[key: string]: string[]} = {
  15. 'Tamilnadu': ['Chennai', 'Coimbatore','Madurai'],
  16. 'Kerala': ['Trivandrum','Kochi','Kollam'],
  17. 'Karnataka': ['Bangalore', 'Mysore'],
  18. 'Maharastra': ['Mumbai', 'Pune']
  19. };
  20. checkboxes = [
  21. { value: '10%off First service visit', name: '10%off First service visit' },
  22. { value: '10%off Waterwash', name: '10%off Waterwash' },
  23. { value: 'Free AC Inspection', name: 'Free AC Inspection' },
  24. ];
  25. //
  26. cars: any[] = [];
  27. //
  28. checkboxValues: string[]=[];
  29. //
  30. get checkboxesFormArray() {
  31. return this.form.controls['checkbox'] as FormArray;
  32. }
  33. constructor(private fb: FormBuilder,private location : Location,private carServiceService :CarServiceService) {
  34. this.form = this.fb.group({
  35. carmodel :['', [Validators.required, Validators.minLength(3)]],
  36. carnum :['', [Validators.required]],
  37. contactNumber: ['', [Validators.required, Validators.pattern(/^\d{10}$/)]],
  38. option: ['', Validators.required],
  39. checkbox: new FormArray([], Validators.required),
  40. state: ['', Validators.required],
  41. city: ['', Validators.required]
  42. });
  43. this.addCheckboxes();
  44. }
  45. addCheckboxes() {
  46. this.checkboxes.forEach(() =>
  47. this.checkboxesFormArray.push(new FormControl(''))
  48. );
  49. }
  50. goBack():void{
  51. this.location.back();
  52. }
  53. onSubmit() {
  54. if (this.form.valid) {
  55. // console.log(this.form.value);
  56. this.carServiceService.addCar(this.form.value).subscribe(response =>{
  57. console.log(response);
  58. this.carServiceService.getCars().subscribe(cars => {
  59. this.cars = cars; // Set the list of cars to the response data
  60. console.log(this.cars);
  61. });
  62. });
  63. } else {
  64. // Form is invalid, display error messages
  65. this.form.markAllAsTouched();
  66. }
  67. }
  68. Reset(){
  69. this.form.reset();
  70. }
  71. onStateChange() {
  72. const state = this.form.controls['state'].value;
  73. this.form.controls['city'].setValue('');
  74. if (state) {
  75. this.form.controls['city'].enable();
  76. } else {
  77. this.form.controls['city'].disable();
  78. }
  79. }
  80. checkedChanged(e:any) {
  81. let index = this.checkboxes.findIndex(
  82. (item) => item.value === e.target.value
  83. );
  84. if (e.target.checked) {
  85. this.checkboxesFormArray.controls[index].setValue(e.target.value);
  86. } else {
  87. this.checkboxesFormArray.controls[index].setValue('');
  88. }
  89. }
  90. }

also got this service named , car-service.service.ts:

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { Observable } from 'rxjs';
  4. import { Form } from '@angular/forms';
  5. @Injectable({
  6. providedIn: 'root'
  7. })
  8. export class CarServiceService {
  9. constructor(private http: HttpClient) { }
  10. addCar(formData : any): Observable<any>{
  11. return this.http.post<any>('https://localhost:7095/api/Forms/submit-form',formData);
  12. }
  13. getCars(): Observable<any[]> {
  14. return this.http.get<any[]>('https://localhost:7095/api/Forms/get-forms');
  15. }
  16. }

Im trying to post my input values of html form from angular to asp.net core web API and then getting those values back to print them below the html form in a table format. I'm able to post every fields and get back those values but there's a small thing that bothers me. In the checkbox field, If I selected the last two checkboxes, I get the values as

  1. ,10%off Waterwash,Free AC Inspection

and on selecting just the last checkbox, I get them like

  1. ,,Free AC Inspection

or on selecting the second checkbox alone, I get the values like,

  1. ,10%off Waterwash,

Basically I want to get rid of the comma in the form array. Can someone tell me how to do that

答案1

得分: 1

你需要创建一个对象,删除数组中的"empty"值。因此,在提交函数中,您可以使用以下代码:

  1. onSubmit() {
  2. if (this.form.valid) {
  3. // 创建一个新对象
  4. const data = {
  5. ...this.form.value, //<--表单的所有值
  6. checkbox: this.form.value.checkbox.filter(x => x)
  7. };
  8. // 发送此对象,而不是form.value
  9. this.carServiceService.addCar(data).subscribe(response => {
  10. // ...
  11. });
  12. }
  13. }

但是,实际上,您的复选框表单数组的值应始终是一个包含true或false的数组,例如[true, true, false]

如果您想要根据复选框的数组值传递给API,您只需要在提交函数中创建一个新对象,将表单的值与"checkbox属性"更改如下:

  1. onSubmit() {
  2. if (this.form.valid) {
  3. const data = {
  4. ...this.form.value, //<--表单的所有值
  5. checkbox: this.form.value.checkbox
  6. // 将会是,例如 [true, false, true]
  7. .map((x: boolean, index: number) => x ? this.checkboxes[index].value : '')
  8. // 将会是,例如 ['10%off First service visit', '', 'Free AC Inspection']
  9. .filter((x: string) => x)
  10. // 将会是,例如 ['10%off First service visit', 'Free AC Inspection']
  11. .join(',')
  12. // 将会是 '10%off First service visit,Free AC Inspection'
  13. };
  14. this.carServiceService.addCar(data).subscribe(response => {
  15. // ...
  16. });
  17. }
  18. }

这样,您就不需要使用您的checkedChanged函数。

注意:我不知道您是想发送数组还是一个由逗号分隔的字符串(如果需要API中的字符串数组,请删除"join")。

注意2:还有另一种方法,不使用FormArray,而是使用一个简单的FormControl,并使用[(ngModel)]来更改FormControl。可以参考这个Stack Overflow链接

英文:

You need create an object removing the "empty" values of the array. So in submit function you can use

  1. onSubmit() {
  2. if (this.form.valid) {
  3. //create a new object
  4. const data={
  5. ...this.form.value, //&lt;--all the value of your form
  6. checkbox:this.form.value.checkbox.filter(x=&gt;x)
  7. }
  8. //send this object, not the form.value
  9. this.carServiceService.addCar(data).subscribe(response =&gt;{
  10. ...
  11. }
  12. }

But really the value of your checkboxesFormArray should be always an array with true or false, e.g. [true,true,false]

As you want to pass to your API the value based in your array checkboxes the only you need are, in submit function, create a new object with the values of the form but the "checkbox property" changed

  1. onSubmit() {
  2. if (this.form.valid) {
  3. const data={
  4. ...this.form.value, //&lt;--all the value of your form
  5. checkbox:this.form.value.checkbox
  6. //will be,. e.g. [true,false,true]
  7. .map((x:boolean,index:number)=&gt;x?this.checkboxes[index].value:&#39;&#39;)
  8. //will be, e.g. [&#39;10%off First service visit&#39;,&#39;&#39;,&#39;Free AC Inspection&#39;]
  9. .filter((x:string)=&gt;x)
  10. //will be,e.g. [&#39;10%off First service visit&#39;,&#39;Free AC Inspection&#39;]
  11. .join(&#39;,&#39;)
  12. //will be &#39;10%off First service visit,Free AC Inspection&#39;
  13. }
  14. this.carServiceService.addCar(data).subscribe(response =&gt;{
  15. ...
  16. }
  17. }

So we needn't use your function checkedChanged

NOTE: I don't know if you want to send the array or a string separate by commas (remove the "join" if you need an array of string in your API.

NOTE2: There're another approach that it's not use a FormArray else a simple FormControl, and use [(ngModel)] to change the FormControl. See this SO

huangapple
  • 本文由 发表于 2023年4月4日 13:59:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定