我看到过类似的问题,但我还是不明白。
我有一个组件女巫获取项目列表 Array<{id: number, name: string}>
和“已检查”项目列表 Array<number>
@Component({
selector: 'check-list',
template: `
<div class="form-check" *ngFor="let item of list">
<label class="form-check-label">
<input class="form-check-input"
type="checkbox"
[checked]="checked.includes(item.id)"
(change)="onChange.emit({id: item.id, value: $event.target.checked})">
{{ item.name }}
</label>
</div>
`
})
export class CheckListComponent {
@Input() list: CheckListItem[];
@Input() checked: number[];
@Output() onChange: EventEmitter<any> = new EventEmitter();
constructor() { }
}
如果我更新“选中”列表,呈现的复选框列表也会更新,但如果我单击某些复选框然后更新“选中”列表,它不会按我预期的方式呈现。
笨蛋:https://plnkr.co/edit/YSItU48QflE4GZbj58Ev?p=preview
单击 plunker 中的两个按钮,它按我预期的那样工作,复选框根据“选中”列表更新。但是如果我点击“item 2”然后点击reset,它不会清除“item 2”。
我也尝试过使用 [ngModel]
和 [attr.checked]
.
我不想使用的原因 [(ngModel)]
是我也有一个@Output()
这会触发服务器请求,然后如果失败,则复选框应该更新或不更新。我正在使用 ngrx
对于州。
更新:
所以我在我的问题中不够清楚我正在使用 Redux/ngrx 并且发送到我的检查列表组件的列表不应该由组件本身直接改变。我已经更新了组件以在更改时发回输出
这是新的插件:https://plnkr.co/edit/lMouWapI2lb9U6mS9YMy?p=preview
更新 2:
所以我遇到的问题是单击/检查会将更新发送到服务器,如果失败,我希望将复选框重置为以前的状态。 如果服务器请求成功与否,我添加了一个随机 bool 值。 也许我为此使用了错误类型的实现 ide。
最佳答案
您还需要更新 check-list
组件中的 checked 数组,以及每次检查更改时,
检查 list
@Component({
selector: 'check-list',
template: `
<div class="form-check" *ngFor="let item of list">
<label class="form-check-label">
<input class="form-check-input"
type="checkbox"
[checked]="checked.includes(item.id)"
(change)="onChange.emit({id: item.id, value: $event.target.checked})">
{{ item.name }}
</label>
</div>
`
})
export class CheckListComponent {
@Input() list: CheckListItem[];
@Input() checked: number[];
@Output() onChange: EventEmitter<any> = new EventEmitter();
constructor() { }
}
应用
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<check-list [list]="list" [checked]="checked"
(onChange)="updateChecked($event)"></check-list>
<button (click)="setFirstChecked()">Set First Checked</button>
<button (click)="resetChecked()">Reset Checked</button>
</div>
`
})
export class App {
....
updateChecked($event) {
// This will be handled in Redux/ngrx...
if ($event.value) {
this.checked.push($event.id);
}
else {
this.checked = this.checked.filter((i) => i !== $event.id);
}
}
...
}
更新了 Plunker!!
关于javascript - 以编程方式设置 Angular 4 复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000515/