gpt4 book ai didi

typescript - Angular 2 使用 ngFor 设置和绑定(bind)复选框

转载 作者:太空狗 更新时间:2023-10-29 19:36:35 25 4
gpt4 key购买 nike

我有一个这样的数组:

 objectArray = [
{"name": "Car"},
{"name": "Bike"},
{"name": "Boat"},
{"name": "Plane"}
];

模板是这样的:

<li *ngFor="#obj of objectArray">
<a href="#" class="small" data-value="option1" tabIndex="-1">
<input type="checkbox" (change)="expression && expression.value = $event.target.checked ? true : undefind" [ngModel]="expression?.value">
<label for="">{{ obj.name }}</label>
</a>
</li>

但是当 1 个复选框被选中时,这将被设置为真。我该如何单独设置它?

最佳答案

我在使用最新版本的 Angular 2 解决这个问题时遇到了一些麻烦。这是我想出的方法,可以双向绑定(bind)到包含 Angular 色名称和 bool 值的对象列表,用于检查 Angular 色。

enter image description here

<form [formGroup]="userInfoForm" (ngSubmit)="onSubmit(userInfoForm)">

...

 <input type="hidden" name="roles" formControlName="roles" [(ngModel)]="roleSelections">
<div *ngFor="let role of roleSelections">
<input type="checkbox"
[value]="role.isChecked"
[checked]="role.isChecked"
(change)="$event.target.checked ? role.isChecked = true : role.isChecked = false">
{{role.name}}
</div>

RoleSelection 只是一个具有两个字段的简单类:

export class RoleSelection {
constructor(
public name: string,
public isChecked: boolean)
{ }
}

在组件中,我必须在创建 FormGroup 时声明一个名为 roles 的属性,然后将其绑定(bind)到上面 HTML 中的隐藏字段。

    this.userInfoForm = new FormGroup({
emailAddress: new FormControl(this.userInfo.emailAddress, Validators.required),
firstName: new FormControl(this.userInfo.firstName, Validators.required),
middleName: new FormControl(this.userInfo.middleName),
lastName: new FormControl(this.userInfo.lastName, Validators.required),
isAdmin: new FormControl(this.userInfo.isAdmin),
isArchived: new FormControl(this.userInfo.isArchived),
roles: new FormControl(this.roleSelections)
});

然后在提交表单时,ngSubmit 方法只需要提取它需要的内容:

 private onSubmit(obj: any) {
if (obj.valid) {
let account: IUserAccount = {};
account.id = this.userAccountId;
account.firstName = obj.controls.firstName.value;
...
...
// get list of roles checked via obj.controls.roles.value[i].isChecked etc
...
...
// do submission
}
}

关于typescript - Angular 2 使用 ngFor 设置和绑定(bind)复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com