Read the benefits of using pipes versus invoking functions in angular templates. see vid here: https://www.youtube.com/watch?v=I6ZvpdRM1eQ
I have this function in my template.html
<h1 [class]="alignText()" [innerHtml]="data.text"></h1>
And the function in my component.template.ts
alignText(): string {
let defaultText = "center";
return "text-" + (this.text || defaultText)
}
Anyone has suggestions how I could concert the html alignText()
to a pipe to accomplish the same result?
Refer to Angular's documentation on Pipes: https://angular.io/guide/pipes
You can use the @Pipe
decorator on a class for pipes. It should implement the PipeTransform
interface which requires implementing a transform
method that takes the value and returns a new value. transform
can take additional arguments if needed.
@Pipe({ name: 'alignClass' })
export class AlignClassPipe implements PipeTransform {
transform(value: string): string {
return `text-${value || "center"}`;
}
}
Add this pipe to declarations
in your module. Now you can use [class]="text | alignClass"