Issue
I'm having some issues to pass a variable from one HTML to its child HTML. Code explanation below:
in app.component.html I'm using ngFor and declaring the variables taskElement and i:
<app-task *ngFor="let taskElement of taskElements; let i=index" [taskElement]="taskElement"></app-task>
And in the app-task child HTML I have a button where I need to use the i variable:
<div class="d-flex justify-content-center">
<li class="list-group-item">
<span>
{{element.description}}
</span>
<button class="btn btn-danger" style="float: right;" type="button" (click)="deleteTask(i)">Remove
Task</button>
</li>
</div>
</ul>
I've also tried to redeclare the ngFor inside app-task, but this was causing the list to be duplicated. Is there a way to use the "i" variable inside the child app-task?
Thanks in advance!
Solution
What I would suggest is using an Output()
in the child component for when the button is clicked. That way, you can handle the logic requiring the index variable i
in the parent component where it is declared, and the child component can stay dumb and happy:
export class TaskComponent {
@Output()
deleteClick = new EventEmitter<void>();
deleteButtonClicked() {
this.deleteClick.next();
}
}
Parent component HTML:
<app-task
*ngFor="let taskElement of taskElements; let i=index"
[taskElement]="taskElement"
(deleteClick)="deleteTask(i)"
></app-task>
Another approach
Instead of forcing the child component to be dumb and the parent component to be smart, another approach, which I think is better personally, is to have both components be dumb and have them both depend on a service class that keeps track of all of your tasks. Since your child component has an Input
for the task element, when the user clicks the delete button in the child component, you could just call the deleteTask
method in this hypothetical service class, and have the collection of tasks be refreshed automatically for the parent component's ngFor
loop.
Answered By - Jake Smith
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.