我有一个父组件
export class ItemsComponent implements OnInit {
itemList: any;
constructor(private itemService:ItemService) {}
ngOnInit() {
this.itemService.getJsonData()
.subscribe(response => {
this.itemList = response;
}, (error) => {
console.log(error);
});
}
selectCheckItemParent(event): void{
for(var counter=0; counter<this.itemList.length;counter++){
if(this.itemList[counter].itemId==event.target.dataset.cid){
this.itemList[counter].isSelected = event.target.checked;
}
}
}
}
和一个子组件
export class ListViewComponent implements OnInit {
@Input() itemList : Item[];
@Output() selectCheckItemParent = new EventEmitter<string,string>();
constructor(private cdr: ChangeDetectorRef) {}
get runChangeDetection() {
console.log('ListView - Checking the view');
return true;
}
selectCheckThisItem(event, itemSelected){
this.selectCheckItemParent.emit(event);
}
}
使用 HTML
<li *ngFor="let item of itemList;" >
<input attr.data-cid="{{item.cid}}" (change)="selectCheckThisItem($event, item)" type="checkbox" class="checkbox-custom" #isSelected ng-class="{ item.isSelected == true : 'checked'}" />
<span class="row items-div" ng-class="{ item.isSelected==true : 'selectedItem' }">
{{item.isSelected}}
</span>
</li>
现在,当检测到任何更改时,li 标签内的这个跨度显示 true/false,但是当 isSelected 为 true 时,ng-class 应该添加“selectedItem”类,这不会发生。