我有兩個組件item-list和item。專案串列組件顯示帶有復選框的專案串列。當在復選框中簽入時,我一直在嘗試將專案推到新陣列,但是該陣列僅在記錄時僅包含最后一個專案。
下面是我試過的代碼,
專案串列.component.html
<div>
<mat-form-field appearance="outline">
<input matInput placeholder="Add a Task" (keyup.enter)="addTask()"autocomplete="off"[formControl]="nameControl"/>
</mat-form-field>
</div>
<app-item
[value]="value"
*ngFor="let value of data; index as index"
>
</app-item>
item.component.html
<div class="listContainer">
<div class="checkContainer">
<mat-checkbox color="secondary" [(ngModel)]="IsChecked" (change)="onChange($event)">
</mat-checkbox>
</div>
</div>
<div class="displayTask">
<div class="displayvalue" [ngClass]="{ 'line-through': value.task }">
{{ value.task | uppercase }}
</div>
</div>
item.component.Ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.scss'],
})
export class ItemComponent implements OnInit {
@Input()
value: any;
IsChecked: boolean;
public ArrayChecked: any[] = [];
constructor() {
this.IsChecked = false;
}
ngOnInit(): void {}
onChange($event: any) {
if ($event.checked) {
this.ArrayChecked.push(this.value.task);
console.log('the task is added', this.ArrayChecked);
}
else console.log('the task is removed');
}
}
在上面的組件專案代碼中,我嘗試將專案推送到 onChange() 內的新陣列“ArrayChecked”,但是當我記錄結果時,該陣列只包含我檢查的最后一個專案。我想獲取在復選框中選中的所有專案的串列。
有人可以幫我修復我的代碼,所以所有選中的專案都在 'ArrayChecked[]' 內。提前致謝!
uj5u.com熱心網友回復:
這里的問題是它ArrayChecked在每個組件中都被初始化item,這意味著每個組件只會將值推送到它自己的ArrayChecked變數。因此,只會記錄最后選中的復選框的值。
這可以通過ArrayChecked在item-list組件而不是item組件中初始化來解決。然后,item組件應在其復選框的值隨專案的任務發生變化時觸發一個事件。然后,您可以在中收聽此事件item-list并將任務推送到ArrayChecked。
專案.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.scss'],
})
export class ItemComponent implements OnInit {
@Input()
value: any;
// Emitted when the task is checked
@Output()
checkTask = new EventEmitter<any>;
IsChecked: boolean;
constructor() {
this.IsChecked = false;
}
ngOnInit(): void {}
onChange($event: any) {
if ($event.checked) {
// We now emit the checkTask event instead of directly pushing it to the array
this.checkTask.emit(this.value.task);
console.log('the task is added', this.ArrayChecked);
}
else console.log('the task is removed');
}
}
專案串列.component.html
<app-item
[value]="value"
(checkTask)="addCheckedTask($event)"
*ngFor="let value of data; index as index"
>
</app-item>
專案串列.component.ts
addCheckedTask($event: any): void {
this.ArrayChecked.push($event);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537503.html
標籤:有角度的打字稿
