[英]How do i target particular iteration of ngFor loop in angular 9 with jQuery?
我有一個使用帶有復選框的 *ngFor 實現的模式中的項目列表。 目標是在單擊復選框時刪除項目的內容。
初始代碼: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:
<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>
發生的問題是當單擊任何復選框時,它將類 .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;
}
單擊此處查看工作示例
即使不在 ts 文件中添加任何額外的函數,您也可以做到這一點。 此外,您不需要 jQuery。
添加一個帶有注釋對象的新布爾字段,例如“已檢查”。
在您的 HTML 中,將此字段與復選框綁定
<input type="checkbox" [checked]="note.checked" class="form-check-input" id="Check">
根據注釋對象的“已檢查”布爾字段將動態 css 類添加到 div 元素。 <div class="note" [ngClass]="{'line-thr': note.checked}" .....>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.