简体   繁体   中英

Reactive form in angular 4 submit array of checkbox values on click of button

I am developing an app in Angular 4. I am using Reactive forms. I am building a simple submit form like below:

<form [formGroup]="newPostForm" novalidate>

      <input formControlName="Title" type="text" class="form-control" id="txtTitle" placeholder="Enter title of post..."> 
        <h4>Categories</h4>
        <ul>
          <li *ngFor="let cat of catsList">
            <span style="margin-top: -2.5px;">
              <input id="CheckBox" type="checkbox" formNameArray="Categories" [value]='cat.CategoryID' checked='false'></span> {{cat.CategoryName}}
          </li>
        </ul>
    <input type="submit" name="btnSubmit" value="Save" id="btnSubmit" (click)="onSubmitedForm()" class="btn btn-primary">
</form>

Below is new-post.component.ts file:

export class NewPostComponent implements OnInit {
  public catsList: any = [];
  public newPostDTO: any = [];
  newPostForm: FormGroup;

  constructor(private _postsSvc: PostsService,
    private _categoriesSvc: CategoriesService,
    private _formGroup: FormBuilder) { }

  ngOnInit() {
    this.getAllCategories();
    this.initProperties(); //init all props
    this.createPostForm(); 
  }


  initProperties() {
    this.newPostDTO = {
      Title: null,
      Content: null,
      Categories: null
    };
  }

  createPostForm() {
    this.newPostForm = this._formGroup.group({
      Title: [''],
      Categories: new FormArray([])
    });
  }

  onSubmitedForm() {
    console.log(this.newPostForm.value.Categories);
    this.newPostDTO = {
      Title: this.newPostForm.value.Title,
      Categories:  this.newPostForm.value.Categories,
    };
    this._postsSvc.addPost(this.newPostDTO).subscribe(data => {
      if (data.status === 201) {

      }
    });
  }


getAllCategories() {
  this._categoriesSvc.getCategories().subscribe(
    data => this.catsList = data.body );
  }

} I want to get all Ids of checked categories as an array when click on submit button. How can I achieve this? I tried but the value of Categories array is null after i CLICK SUBMIT button.

Thank you to all!

Reactive form source of control is class not a template, so if you want to create dynamic check box you need to create multiple formControl

If you want the Changes to be happened only after submit you can pass the {updateOn:"submit"} to get data only after submit

catsList = [{cName:"cat1"},{cName:"cat2"},{cName:"cat3"}];

  newPostForm: FormGroup;
  constructor(private fb: FormBuilder) {
    const control = this.catsList.map((d)=>new FormControl())
    this.newPostForm = this.fb.group({
      Title: [''],
      Categories: new FormArray(control,{updateOn:"submit"})
    })
  }

  get catControl() {
    return this.newPostForm.get('Categories')['controls'];
  }

  onSubmitedForm() {

  }

FormArray is based on index so we should use index for individual formControl

<form [formGroup]="newPostForm" > 
    <input formControlName="Title" type="text" class="form-control" id="txtTitle" placeholder="Enter title of post..."> 
        <h4>Categories</h4>
        <ul>
          <li *ngFor="let cat of catControl;let i =index">
            <span style="margin-top: -2.5px;" formArrayName="Categories">
              <input  [formControlName]="i" id="CheckBox" type="checkbox"  ></span> {{catsList[i].cName}}
          </li>
        </ul>
    <input type="submit" name="btnSubmit" value="Save" id="btnSubmit" (click)="onSubmitedForm()" class="btn btn-primary">
</form>

Example: https://stackblitz.com/edit/angular-dzxcf1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM