Issue
I have an action bar in Angular 12, with several icons. When user clicks on one of them, a new division/Panel opens up. Now, when one icon is clicked, only that panel has to open up, and the others are closed. I created an interface for setting which panel is active.
export interface PanelModel{
apps : boolean;
payroll: boolean;
chat : boolean;
mycloud: boolean;
}
In my service I have initialized the Interface with
public chosen: PanelModel = {
apps:false,
payroll:false,
chat:false,
mycloud:false
};
Now if apps icon is clicked, I would like to set the this.chose.apps = true and then set payroll, chat, mycloud variables to false.
How do I set the values of the interface?
Solution
If I understand you correctly, you want to iterate through the keys and dynamically set the selected icon to true and the rest to false, so if this is the case then the below should solve your issue.
// Your interface.
interface PanelModel{
[apps: string]: boolean;
payroll: boolean;
chat : boolean;
mycloud: boolean;
};
// Object that implements your interface with default values.
const chosen: PanelModel = {
apps: false,
payroll: false,
chat : false,
mycloud: false
};
// Your clicked icon (as an example).
const clickedIcon = 'apps'
// Log what it looks like before.
console.log('BEFORE: ', chosen);
// Iterate through the keys to find the one to set to true and set rest to false.
Object.keys(chosen).map(key => {
if(key === clickedIcon) {
chosen[key] = true;
} else {
chosen[key] = false;
}
});
// Below is doing the same as above but in a single line of code.
// Object.keys(chosen).map(key => key === clickedIcon? chosen[key] = true : chosen[key] = false);
// Log output.
console.log('AFTER: ', chosen);
Since you specifically mention Angular 12, you can hook the button click to a function which passes the $event (name of icon or whatever) to a method which does this iteration specifically. (assuming your rendering your buttons dynamically then you can pass the name directly rather then event)
// Method in your typescript component file
onIconClick(tabName: string): void {
Object.keys(chosen).map(key => {
if(key === tabName) {
chosen[key] = true;
} else {
chosen[key] = false;
}
});
}
// Your HTML component file (if buttons a rendered dynamically)
<div *ngFor="let tab of tabs">
<button type="button" class="button (click)="onIconClick(tab)">{{tab}}</button>
</div>
Answered By - VVS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.