0

I have the following code in a template from an Angular 4 app using ngx-translate

<a [routerLink]="['birthdays']" [title]="'birthdays.title' | translate">
{{ 'birthdays.title' | translate }}
</a>

this works perfect. But I have to duplicate the code that retrieves the translate for 'birthdays.title'. Is there a way to, in the template, set it to a variable and use this variable?

Something like (pseudo code):

<a [routerLink]="['birthdays']" [title]="'birthdays.title' | translate as title">
{{ title }}
</a>
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
  • wrap it in a `BirtdaysLink` component or look here [`how to simulate ng-init`](https://stackoverflow.com/a/41868229/4099454) – Hitmands Sep 27 '17 at 16:40
  • @Hitmands this solves the problem but does not 'scale': I would have to add one attribute in the component for each translation. If my template have 100 translation keys, the component must have 100 attributes too. – Christian Benseler Sep 27 '17 at 16:54

1 Answers1

0

I don't think this is needed but you could make a get variable in your .ts and then use that variable in your html:

// This is needed because translate get is async :(
birthdayString: string = '';

ngAfterViewInit() {
    this.translate.get('birthdays.title')
        .subscribe(value => { this.birthdayString = value; })
}

get birthdayText() {
    return birthdayString;
}

And in your html file:

<a [routerLink]="['birthdays']" [title]="birthdayText">
    {{ birthdayText }}
</a>
assisrMatheus
  • 445
  • 1
  • 5
  • 17
  • I already knew this is possible, but I don't want to do this in the component (.ts), as long as my template can have multiple translations, so I would need to create one attribute for each translation. That's way in the question I mentioned that I wanted to threat this in the .html file. Anyway thanks for the help. – Christian Benseler Sep 27 '17 at 16:53