How to pass a string from HTML to the Component on Angular 8 using (click) function?

1k views Asked by At

I have this code and it works fine:

<a [routerLink]="['/menuItemOne']">
    <span [innerHTML]="(mystrings$ | async)?.menuItemOne | htmlToText"></span>
</a>

But now I need to update the page title when the link is clicked.

I added a setTitle method on the component:

public setTitle( newTitle: string) {
   this.titleService.setTitle( newTitle );
}

Using (click) function I can update the page title and it works fine:

<a [routerLink]="['/menuItemOne']" (click)="setTitle('Menu Item One')">
    <span [innerHTML]="(strings$ | async)?.menuItemOneStr | htmlToText"></span>
</a>

But how do I do it to pass the variable menuItemOneStr instead of using the string 'Menu Item One'?

I tried:

<a [routerLink]="['/menuItemOne']" (click)="setTitle((strings$ | async)?.menuItemOneStr | htmlToText)">
    <span [innerHTML]="(strings$ | async)?.menuItemOneStr | htmlToText"></span>
</a>

But it doesn't work. Any ideas?

1

There are 1 answers

3
Vorpal56 On BEST ANSWER

You can subscribe to it on your setTitle method

public setTitle(key: string) {
    // key = menuItemOneStr, menuItemTwoStr, etc.
    this.strings$.subscribe((stringsObject: object) => {
        this.titleService.setTitle(stringsObject[key]);
    })
}

And in your HTML

<a [routerLink]="['/menuItemOne']" (click)="setTitle('menuItemOneStr')">
    <span [innerHTML]="(strings$ | async)?.menuItemOneStr | htmlToText"></span>
</a>

This means your subscribing to it twice, since the async pipe subscribes aswell. It seems like your strings$ is Observable<object>[] so you can can use ngFor and subscribe once. This means your setTitle stays the same but the HTML is changed. As a note, you can use interpolation inside any tags with pipes using the {{ variableName | somePipe }} notation.

Updated HTML

<ng-container *ngFor="let stringDetails of strings$ | async; index as i">
    <a [routerLink]="[stringDetails.link]" (click)="setTitle(stringDetails.title)">
        <span>{{stringDetails.text | htmlToText}}</span>
    </a>
</ng-container>