3

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!

1
  • You would get the answer much faster if you provide a stackblitz reproduction Commented Dec 27, 2018 at 0:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.