Reputation: 23
I have an Angular component function which returns a string I need to show in my HTML. The function works, but the html tag generates as empty.
Function:
getTaskNameById(id: any): string {
console.log('function start; id = ' + id);
this.tasks.forEach(e => {
if (e.idTask === Number(id)) {
console.log('if statement true; name = ' + e.name);
return e.name;
}
});
return '';
}
HTML:
{{ getTaskNameById(form.value.tasks[i]) }}:
[Console log][1]
[Page look][2]
[Generated HTML][3]
[1]: https://i.sstatic.net/Pasl0.png
[2]: https://i.imgur.com/0CKhxLt.png
[3]: https://i.imgur.com/YSkJJrY.png
Upvotes: 1
Views: 338
Reputation: 24414
you don't need to use a method to get the task name because you already have an instant of the taks items when you loop throw the array like this
<label *ngFor="let t of tasks; let i = index">
id {{t.idTask}} , name {{ t.name }}<br>
</label>
Upvotes: 0
Reputation: 6257
Your string is empty because it is not possible to return inside of Array.forEach
.
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
See the docs for more information.
You need to change it to a normal for-loop
or you can use some Array build in functions, like Array.find
. See following:
getTaskNameById(id: any): string {
console.log('function start; id = ' + id);
const task = this.tasks.find(t => t.idTask === +id);
if (task) return task.name;
return '';
}
Upvotes: 2