💻 Tech
We can bind a function with a property of a DOM element. [src]
means the value of src
property changes based on the returned value of the imagePath
getter function. Why use get
? It allows the function to be implicitly called if bound to a property, like to src
in the example. If you remove get
, you will need to explicitly call the function like so: imagePath()
. This means if a function is meant to be accessed like a property, you should define it with a get
.
<div>
<button>
<img [src]="imagePath" [alt]="user.name"/>
<span>{{user.name}}</span>
</button>
</div>
import { Component } from '@angular/core';
import { generateUser } from '../user_generator';
@Component({
selector: 'app-user',
standalone: true,
imports: [],
templateUrl: './user.component.html',
styleUrl: './user.component.css'
})
export class UserComponent {
user = generateUser();
get imagePath(){
return 'assets/avatars/' + this.user.avatar;
}
}