Now all that's missing is the button functionality. This component should allow the user to provide a single up or down vote rating and give visual feedback to the user. In this step you'll do some setup work:
Add a new vote property and attribute, like the rating property you added previously.
Add new styles for the vote-up and vote-down buttons based on the current value of the vote attribute.
Then in the following step you'll add the event listeners to handle button clicks and set the vote attribute.
In shadow DOM the :host selector refers to the node or custom element that the shadow root is attached to.
In this case, if the vote attribute is "up" (e.g. <rating-element vote="up">) it will turn the thumb-up button green.
If vote is "down" (e.g. <rating-element vote="down">), then it will turn the thumb-down button red.
Now, implement the logic for this by creating a reflecting property / attribute for vote similar to how you implemented rating. Start with the property setter and getter:
exportclassRatingElementextendsHTMLElement {
private_rating=0;
private_vote: 'up'|'down'|null=null;
...
setvote(newValue) {
constoldValue=this._vote;
if (newValue===oldValue) {
return;
}
if (newValue==='up') {
if (oldValue==='down') {
this.rating+=2;
} else {
this.rating+=1;
}
} elseif (newValue==='down') {
if (oldValue==='up') {
this.rating-=2;
} else {
this.rating-=1;
}
}
this._vote=newValue;
this.setAttribute('vote', newValue!);
}
getvote() {
returnthis._vote;
}
}
exportclassRatingElementextendsHTMLElement {
_vote = null;
...
setvote(newValue) {
constoldValue=this._vote;
if (newValue===oldValue) {
return;
}
if (newValue==='up') {
if (oldValue==='down') {
this.rating+=2;
} else {
this.rating+=1;
}
} elseif (newValue==='down') {
if (oldValue==='up') {
this.rating-=2;
} else {
this.rating-=1;
}
}
this._vote=newValue;
this.setAttribute('vote', newValue);
}
getvote() {
returnthis._vote;
}
}
Initialize the _vote instance property with null as a class-member property, and in the setter, check if the new value is different. If so, adjust the rating accordingly and, importantly, reflect the vote attribute back to the host with this.setAttribute.
It is not recommended to manipulate rating inside the vote setter in this way.
This is not the most efficient way to update rating, but it's the most convenient way for this tutorial.