I would like to understand how an Angular component re-render to display the new information whenever there is a change in the underlying data. (eg. push/delete)
I have the following component that uses a data service to get the data. When the component is first initialised, the constructor is executed and existing data is retrieved if any.
Table.component.ts
export class TableComponent implements OnInit {
table : Task[]
dropdowns = ["green", "yellow", "red"]
taskName : string
taskStatus : string
@ViewChild('form') form: NgForm
constructor(private tableService : TableService) {
// if I comment the line below my table does not get updated when submitTask() is run.
this.table = tableService.getData();
}
submitTask() {
const taskName : string = this.form.form.value.taskName
const taskStatus : string = this.form.form.value.taskStatus
const task: Task = {item: taskName, status: taskStatus}
this.tableService.addData(task)
}
ngOnInit(): void {
}
}
Table.service.ts
export class TableService {
tableData : Task[] = []
constructor() { }
addData(task : Task) {
this.tableData.push(task)
}
getData() : Task[] {
return this.tableData
}
}
the submitTask()
function of the component uses the tableService
to update the table
data source. Whenever submitTask()
is called, it seems that the this.table
array suddenly gets updated as well. Is the constructor of the TableComponent
called again ? I am not sure of the angular workflow for handling data changes.