使用Angular 6中的ChangeDetectionStrategy,需要在子元素(ng类)上添加条件类



我有一个父组件

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标记中的这个span显示true/false,但当isSelected为true时,ng类应该添加"selectedItem"类,但这并没有发生。

将对象传递给ngClass时,是要添加的类。是将添加或删除该类的truthy或falsy表达式。

ngClass指令应该用camelCase编写,并且应该用方括号括起来,方括号告诉Angular将值作为模板表达式进行计算。

所以你的表情应该是这样的:

<span [ngClass]="{ selectedItem: item.isSelected }">

最新更新