我有一个 PrimeNG 复选框列表。我有一个用
ngModel
绑定到它的数组,称为 selectedItems
。我还初步检查了该数组中的项目。我遇到一种情况,我不是通过选中复选框而是通过执行其他操作(调用函数)来向 selectedItems
添加项目。例如,通过单击位于其他位置的按钮。我的问题是我可以看到,当我控制台日志时,该项目已添加到 selectedItems
数组中,但视图尚未更新。
这是我用来测试的代码
selectedItems: any[] = [{ name: 'Accounting', key: 'A' }];
items: any[] = [
{ name: 'Accounting', key: 'A' },
{ name: 'Marketing', key: 'M' },
{ name: 'Production', key: 'P' },
{ name: 'Research', key: 'R' }
];
selectSomething(){
this.selectedItems.push({ name: 'Production', key: 'P' })
}
和模板
<div class="card flex justify-content-center">
<div class="flex flex-column gap-2">
<div *ngFor="let item of items" class="field-checkbox">
<p-checkbox name="group" [value]="item" [(ngModel)]="selectedItems" [inputId]="item.key" ></p-checkbox>
<label [for]="item.key">{{ item.name }}</label>
</div>
</div>
</div>
<button (click)="selectSomething()">Select Something</button>
问题在于,当您使用
push()
添加项目时,Angular 更改检测系统不会立即检测到数组中的更改。 ChangeDetectorRef
服务可用于在 selectedItems
数组被修改时启动更改检测并更新显示。具体方法如下:
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent {
selectedItems: any[] = [{ name: 'Accounting', key: 'A' }];
items: any[] = [
{ name: 'Accounting', key: 'A' },
{ name: 'Marketing', key: 'M' },
{ name: 'Production', key: 'P' },
{ name: 'Research', key: 'R' }
];
constructor(private cdr: ChangeDetectorRef) {}
selectSomething() {
this.selectedItems.push({ name: 'Production', key: 'P' });
// Trigger change detection to update the view
this.cdr.detectChanges();
}
}