0

I have an Angular Project and in one component i want to show data by calling a function to the corresponding component.ts.

For example (very simplified)

<div *ngFor="let article of article">
  <h1>{{getTitle(article)}}</h1>
</div>

If i check a console.log in the getTitle function there are a lot of logs, thus the function gets triggerd due to angular events to rerender i would say.

Now i am thinking maybe it is not the best idea to do it in this way? Assumed lot of data in a ngfor loop are shown. What do you think?

3
  • 2
    Definitely not the way to do it. In your controller, set a title property on the articles when the list changes. Function calls In template are almost universally bad Commented Jul 2, 2020 at 16:53
  • you are already using ngfor which means you are iterating an array of I assume objects. shouldn't your title be there? Commented Jul 2, 2020 at 17:02
  • yea it is there, it was just a very simplified example. In praxis i do calculations there... Commented Jul 2, 2020 at 20:19

1 Answer 1

2

You can do something like this.

component.ts:

class Article
{
title:string
author:string
}
articles=[
new Article("title1","author1"),
new Article("title2","author2")
];

component.html:

<div *ngFor="let article of article">
  <h1>{{article.title}}</h1>
</div>
Sign up to request clarification or add additional context in comments.

4 Comments

yes your data should be set up to include title as part of your data. don't try calling a function from your html. that is never a good idea.
can you also say why its a bad idea, just getting trouble with performance or are there other reasons?
Accept the answer if it satisfied you. Thank you.
@Dalitos If you are working on long list of objects, the function has to run each time. In this method all those resources are saved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.