[英]How do i target particular iteration of ngFor loop in angular 9 with jQuery?
I have a list of items inside a modal implemented using *ngFor with check boxes.我有一个使用带有复选框的 *ngFor 实现的模式中的项目列表。 the objective is to strike out contents of item when checkbox is clicked.
目标是在单击复选框时删除项目的内容。
initial code: jQuery in home.component.ts初始代码:home.component.ts 中的 jQuery
$('body').on('click','#Check',function(){
if($(this).is(":checked")) {
$('.note').addClass('line-thr');
} else {
$('.note').removeClass('line-thr')
}
}
); );
home.component.html: home.component.html:
<div class="form-check d-flex" *ngFor= 'let note of notes; let i = index'>
<input type="checkbox" class="form-check-input" value="supress" id="Check">
<div class="check-label note " id="{{i}>
{{note.text}}
<div class="float-right note">
{{note.date}}
</div>
</div>
</div>
The problem that occurs is when clicking on any checkbox, it adds class .line-thr to whole list.发生的问题是当单击任何复选框时,它将类 .line-thr 添加到整个列表中。 BUT I ONLY NEED TO STRIKE OUT THE ELEMENTS IN THAT PARTICULAR ITEM.
但我只需要删除该特定项目中的元素。
The solution could be to use an index number to make a different id for every list item, but I am not sure how to use this variable id in Javascript.解决方案可能是使用索引号为每个列表项创建不同的 id,但我不确定如何在 Javascript 中使用此变量 id。
Using JQuery within angular will be a constant and sizeable challenge for you... it is advisable to avoid it.在 angular 中使用 JQuery 对您来说将是一个持续且相当大的挑战……建议避免它。
You could do it in angular (without JQuery)你可以用 angular 来做(没有 JQuery)
<input type="checkbox" class="form-check-input" value="supress" id="Check" (click)="noteClicked($event, note)">
<div class="check-label note " id="{{i}" [ngClass]="{'line-thr': note.checked}">
{{note.text}}
<div class="float-right note">
{{note.date}}
</div>
</div>
and in your component并在您的组件中
noteClicked($event, note) {
note.checked = $event.currentTarget.checked;
}
Click here for Working example单击此处查看工作示例
You can do that even without adding any extra function in the ts file.即使不在 ts 文件中添加任何额外的函数,您也可以做到这一点。 Also, you do not need jQuery.
此外,您不需要 jQuery。
Add a new boolean field with the note object such as "checked".添加一个带有注释对象的新布尔字段,例如“已检查”。
In your HTML, bind this field with the checkbox在您的 HTML 中,将此字段与复选框绑定
<input type="checkbox" [checked]="note.checked" class="form-check-input" id="Check"> <input type="checkbox" [checked]="note.checked" class="form-check-input" id="Check">
Add dynamic css classes to your div element based on that "checked" boolean field of the note object.根据注释对象的“已检查”布尔字段将动态 css 类添加到 div 元素。 <div class="note" [ngClass]="{'line-thr': note.checked}" .....>
<div class="note" [ngClass]="{'line-thr': note.checked}" .....>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.