I am learning Vue.js and I tried the keep-alive
and component
mechanism which allows to dynamically switch between components. As far as I have understood, I can do something like this:
<template>
<section>
<button @click="setSelectedTab('section-a')">Section A</button>
<button @click="setSelectedTab('section-b')">Section B</button>
</section>
<keep-alive>
<component :is="selectedTab"></component>
</keep-alive>
</template>
export default defineComponent({
name: "SomeComponent",
components: {
SectionA,
SectionB,
},
data() {
return {
selectedTab: 'section-a',
};
},
methods: {
setSelectedTab(tab: string): void {
this.selectedTab = tab;
},
},
});
</script>
The above code will show either SectionA
or SectionB
component according to which button is clicked, while also making sure that the component which is not shown stays alive, keeping its internal state.
In Angular, I would have to do the following:
import { Component } from '@angular/core';
@Component({
selector: 'app-some',
template: `
<section>
<button (click)="setSelectedTab('section-a')">Section A</button>
<button (click)="setSelectedTab('section-b')">Section B</button>
</section>
<app-section-a *ngIf="selectedTab === 'section-a'"></app-section-a>
<app-section-b *ngIf="selectedTab === 'section-b'"></app-section-b>
`,
styleUrls: ['./resources.component.scss']
})
export class SomeComponent {
selectedTab = 'section-a';
setSelectedTab(tab: string): void {
this.selectedTab = tab;
}
}
I guess if I wanted to keep the internal state of the component, I should use the following:
<app-section-a [ngStyle]="{ display: selectedTab !== 'section-a' ? 'none' : 'block' }"></app-section-a>
<app-section-b [ngStyle]="{ display: selectedTab !== 'section-b' ? 'none' : 'block' }"></app-section-b>
Is there a better way to achieve Vue.js behaviour in Angular?