【发布时间】:2019-05-25 02:00:56
【问题描述】:
我正在使用 Angular 4 开发应用程序。我正在使用响应式表单。我正在构建一个简单的提交表单,如下所示:
<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>
下面是new-post.component.ts文件:
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 );
}
} 单击提交按钮时,我想将所有已检查类别的 ID 作为数组获取。我怎样才能做到这一点? 我试过了,但是点击提交按钮后,类别数组的值为空。
谢谢大家!
【问题讨论】:
-
如果您提供 stackblitz 复制,您会更快地得到答案
标签: angular angular2-forms angular-reactive-forms