1

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
3
  • Can you share a copy in stackbiltz Commented Sep 19, 2019 at 8:29
  • I'm sorry about the bad format, the html part should be in a label tag, the page would not allow me to post no matter how I formatted the code Commented Sep 19, 2019 at 8:29
  • @AdritaSharma stackblitz.com/edit/angular-2pbass Commented Sep 19, 2019 at 8:34

2 Answers 2

2

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 '';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great, happy to help =)
0

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>

demo 🚀🚀

1 Comment

This was just a demo to showcase the problem, i'm looping through different items in the html hence the need for function. But thank you anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.