Hiago Koziel
Hiago Koziel

Reputation: 57

Use a variable from one component in another (between .ts files) on Angular

So basically I have a todo list being added dynamically and I want to exclude the items, however the list itself is outside the task component:

In the task.component.html, the list is being iterated to be displayed:

<ul class="list-group" *ngFor="let taskElement of taskElements; let i=index" [taskElement]="taskElement">
<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">Remove
            Task</button>
    </li>

However the list is defined on the file app.component.ts:

public containsTask = false;
  taskElements: { description: string, isDone: boolean }[] = [];

  onTaskCreated(taskData: { taskDescription: string }) {
    this.taskElements.push({
      description: taskData.taskDescription,
      isDone: false
    });
    this.containsTask = true;
  }

How can I use the array taskElements (declared in app.component.ts) in the task.component.ts?

Thanks!

Upvotes: 0

Views: 759

Answers (1)

Nathan van Jole
Nathan van Jole

Reputation: 513

You can use a service to centralise the data. The service can then be injected into both components and this way you can access the array defined inside of the service.

Upvotes: 2

Related Questions