Reputation: 724
I have an item on which I can perform multiple actions (edit, delete, copy, upgrade, ...). There's always only one action which can be performed depending on the status of the item.
So I want to create a button component in Angular to show on the item page and depending on the status I would:
What is the best design for this use case (knowing that the number of scenario's/actions might grow in the future)?
Upvotes: 1
Views: 1573
Reputation: 48
I think the cleanest way is to create a simple component with an @Input() State: string; property to receive a simple state. (As mentioned above)
Then create a const with your possible objects and select properties like text, css styles and functions from it.
const possibilities = {
Edit: {
Text: "Edit",
Color: "Orange",
Function: this.edit
},
Add: { ... }
}
Then simply access the Objects by the state possibilities[state].color or write own getter functions.
Then you have a simple component managing all the stuff and you just need to provide a state.
Maybe consider what to do when a wrong state gets provided ;)
Upvotes: 1
Reputation: 2253
Based on the details specified in the question, one way to approach this would be to create a component with a status
input.
Then, depending on the complexity of your component's template, you can set the property values (e.g. label
property), and the target action in the component class, e.g.:
ngOnInit() {
switch(status) {
case 'Open':
this.label = 'Edit'
...
}
}
...
onButtonClick() {
switch(status) {
case 'Open':
this.action.emit('edit');
...
}
}
If you have a fancier button with complex look and feel based on the status, you could also in the component's template, use the ngSwtichCase
directive like in this documentation: https://angular.io/guide/built-in-directives#the-ngswitch-directives
<div [ngSwitch]="status">
<div *ngSwitchCase="'Open'">..</div>
<div *ngSwitchCase="'Closed'">..</div>
...
</div>
Also, take a look at this Material Button component's API for a reference.
Considering that the number of statuses can grow, but would still be limited, you can achieve a highly customizable button using this approach, and follow the Angular best practices at the same time.
When it comes to the action, you can simply emit an event, and have the parent component perform the necessary action (e.g. call a service method, etc.).
That way your button component stays a "dumb" component.
Upvotes: 1