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!