I have an anchor tag in the web page whose href value depends on a service whose properties are not under control of this component. The service details are populated asynchronously.
To get the service details and create the href value, I thought of two approaches. My question is - Which is better in terms of performance ? What should be the better option ?
Using function as href atribute
This causes the function to be invoked continuously.
// Inside component.html
<div>
<a [href]="getDetailsLink()"></a>
</div>
// Inside component.ts
@Component({ selector: 'user', template: `...` })
class UserComponent implements DoCheck {
public detailsLink: string;
constructor(
private userService: UserService
) {
}
public getDetailsLink(): string {
// Based on the below property
const checkSomeProperty = this.userService.checkSomeProperty;
// Construct details link
this.detailsLink = `https://www.something.com/users/${this.userService.checkSomeProperty.someValue}`;
}
}
Using ngDoCheck
// Inside component.html
<div>
<a [href]="detailsLink"></a>
</div>
// Inside component.ts
@Component({ selector: 'user', template: `...` })
class UserComponent implements DoCheck {
public detailsLink: string;
constructor(
private userService: UserService
) {
}
ngDoCheck() {
if (this.userService.checkSomeProperty) {
// Check changes for the property
// Perform required action
// Construct details link
this.detailsLink = `https://www.something.com/users/${this.userService.checkSomeProperty.someValue}`;
}
}
}
Thank you for reading it till here. Any guidance is appreciated
You have some business logic to generate that url and services is the place for business logic. Solution one is the way to go here.
That being said, based on the fact that the
https://www.something.com/users/part of the link is static or not I would also think about using a pipe for building such a url, to take advantage of memoization.You would end up having something like: