I have a couple of reusable components that have certain filters. I want these filters to be saved to localstorage. However since these components are reüsable i need some kind of unique id for each component because otherwise the filterkeys would all be the same for each component.
For example I have organizations and domains with 1:m relation (1 organization, many domains). I then have a domain-table component, listing a couple domains: (all samples below are excerpts)
@Component({
selector: 'app-domain-table',
templateUrl: 'component.html',
styleUrls: ['component.scss']
})
export class DomainTableComponent implements OnInit {
// filter:
@Input()
organizationId: string;
}
I then reüse this component on 2 pages, the domain page and the organization page:
<div class="head d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-2 pb-2 mb-3 border-bottom fix-width">
<div class="head-start">
<i class="fa fa-users"></i>
<h1 class="h2">Domains</h1>
</div>
</div>
<app-domain-table></app-domain-table>
<div class="head d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-2 pb-2 mb-3 border-bottom fix-width">
<div class="head-start">
<i class="fa fa-orgs"></i>
<h1 class="h2">Organizations</h1>
</div>
</div>
<app-organization-table></app-organization-table>
<app-domain-table></app-domain-table>
No when i want to filter domains for specific organizations i simply set the organizationId
and the component will handle the rest. I've set it up to remember this value between pages like so:
private _organizationId: number = (+localStorage.getItem('DomainTableComponent._organizationId')) ?? 0;
public get organizationId(): number {
return this._organizationId;
}
public set organizationId(value: number) {
localStorage.setItem('DomainTableComponent._organizationId', value ? value.toString() : (0).toString());
this._organizationId = value;
}
This however causes the filter on DomainTableComponent
to be the same for both pages. This is because they use the same key: DomainTableComponent._organizationId
. I need to identify the component instance uniquely in some way, so i can make a key like: DomainTableComponent._organizationId.InstaceOnDomainPage
.
Edit: This question poses a good solution: How to access components unique encapsulation ID in Angular 9