我如何使用 jQuery 定位 angular 9 中 ngFor 循环的特定迭代?
How do i target particular iteration of ngFor loop in angular 9 with jQuery?
我在使用带复选框的 *ngFor 实现的模式中有一个项目列表。
objective是点击复选框时删除项目的内容。
初始代码:jQuery in home.component.ts
$('body').on('click','#Check',function(){
if($(this).is(":checked")) {
$('.note').addClass('line-thr');
} else {
$('.note').removeClass('line-thr')
}
}
);
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>
出现的问题是单击任何复选框时,它会将 class .line-thr 添加到整个列表。但我只需要删除该特定项目中的元素。
解决方案可能是使用索引编号为每个列表项创建不同的 ID,但我不确定如何在 Javascript.
中使用此变量 ID
在 angular 中使用 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>
并在您的组件中
noteClicked($event, note) {
note.checked = $event.currentTarget.checked;
}
点此查看Working example
即使不在 ts 文件中添加任何额外函数,您也可以做到这一点。另外,你不需要 jQuery.
添加一个带有注释对象的新布尔字段,例如“checked”。
在您的HTML中,将此字段与复选框绑定
添加动态 css classes 到你的 div 元素基于笔记对象的那个“检查”布尔字段。
我在使用带复选框的 *ngFor 实现的模式中有一个项目列表。 objective是点击复选框时删除项目的内容。
初始代码:jQuery in home.component.ts
$('body').on('click','#Check',function(){
if($(this).is(":checked")) {
$('.note').addClass('line-thr');
} else {
$('.note').removeClass('line-thr')
}
}
);
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>
出现的问题是单击任何复选框时,它会将 class .line-thr 添加到整个列表。但我只需要删除该特定项目中的元素。
解决方案可能是使用索引编号为每个列表项创建不同的 ID,但我不确定如何在 Javascript.
中使用此变量 ID在 angular 中使用 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>
并在您的组件中
noteClicked($event, note) {
note.checked = $event.currentTarget.checked;
}
点此查看Working example
即使不在 ts 文件中添加任何额外函数,您也可以做到这一点。另外,你不需要 jQuery.
添加一个带有注释对象的新布尔字段,例如“checked”。
在您的HTML中,将此字段与复选框绑定
添加动态 css classes 到你的 div 元素基于笔记对象的那个“检查”布尔字段。