我有一个工作的用户创建表单,我想添加一些复选框作为功能。但是,我无法做到。如果有人能告诉我,我感激不尽。
用户-create.component.html:
<form role="form">
<input name="name" type="text" #userName>
<input name="surname" type="text" class="form-control" #userSurname>
<div class="form-group form-md-checkboxes" *ngIf="roles">
<input name="roles[]" type="checkbox" *ngFor=let role of roles" value="{{role.id}}" #userRoles>
</div>
<button (click)="add(userName.value, userSurname.value, userRoles);" type="button">Create</button>
</form>
users.component.ts:
add(name: string, surname: roles: any): void {
name = name.trim();
surname = surname.trim();
this.userService.create(name, surname, roles);
}
user.service.ts:
create(name: string, surname: string roles: any): Promise<User> {
return this.http
.post(this.usersUrl, JSON.stringify({name: name, surname: surname, roles: roles}), {headers: this.headers})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
我可以成功获取userName和userSurname值,但userRoles始终未定义。
感谢任何帮助。
P.S:我在添加函数中尝试了userRoles.value,在输入定义中也尝试了#userRoles [role.id]。
答案 0 :(得分:-1)
<form role="form">
<input name="name" type="text" #userName>
<input name="surname" type="text" class="form-control" #userSurname>
<div class="form-group form-md-checkboxes" *ngIf="roles">
<input name="roles[]" type="checkbox" *ngFor=let role of roles" value="{{role.id}}" id="userRoles">
</div>
<button (click)="add(userName.value, userSurname.value, userRoles);" type="button">Create</button>
</form>
答案 1 :(得分:-1)
最后,我最终运行了一个价值变化功能。
用户-create.component.html:强>
<form role="form">
<input name="name" type="text" #userName>
<input name="surname" type="text" class="form-control" #userSurname>
<div class="form-group form-md-checkboxes" *ngIf="roles">
<input name="roles[]" type="checkbox" *ngFor=let role of roles" value="{{role.id}}" (change)="onRoleSelectionChange($event, role.id)">
</div>
<button (click)="add(userName.value, userSurname.value);" type="button">Create</button>
</form>
<强> users.component.ts:强>
selectedRoles: any;
ngOnInit() {
this.selectedRoles = [];
}
onRoleSelectionChange(e, role: number): void {
if(e.target.checked)
this.selectedRoles.push(role);
else{
let index = this.selectedRoles.indexOf(role);
if (index > -1) {
this.selectedRoles.splice(index, 1);
}
}
}
add(name: string, surname: string): void {
name = name.trim();
surname = surname.trim();
this.userService.create(name, surname, this.selectedRoles);
}
<强> user.service.ts:强>
create(name: string, surname: string, roles: any): Promise<User> {
return this.http
.post(this.usersUrl, JSON.stringify({name: name, surname: surname, roles: roles}), {headers: this.headers})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}