When you click the button, it decreases the initial set number by 1. However, I would like it to stop at 0

Here is my Quote class where the up-vote and down-vote properties are initially set to 0

export class Quote {
    showDescription: boolean;
    upvotes: number;
    downvotes: number;
    constructor(
    public content:string,
    public publisher:string,
    public author:string,
    public datePublished:Date
    ) {
        this.showDescription = false;
        this.upvotes =  0;
        this.downvotes = 0;
    }
}

Displayed below is the HTML button snippet:

<li *ngFor = 'let quote of quotes; let i = index' quotes>
<div class="col-md-6 downvotes">
................

    <img src="assets/down-arrow.png" alt="" (click)="downVote(i)">
    <span >{{quote.downvotes}}</span>

...................
</div>
</li>

This shows how I'm invoking the downvote function upon clicking the button

import { Component, OnInit } from '@angular/core';
import { Quote } from '../quote'

@Component({
  selector: 'app-quote',
  templateUrl: './quote.component.html',
  styleUrls: ['./quote.component.css']
})

export class QuoteComponent implements OnInit {
............

  downVote(index:number) {
  this.quotes[index].downvotes -= 1;

.................

}

Answer №1

Adjusting the downvotes count for a specific quote at the given index:
this.quotes[index].downvotes -= 1;
Ensuring that the downvotes count does not go below zero:
if (this.quotes[index].downvotes < 0) this.quotes[index].downvotes = 0;

Answer №2

There are numerous strategies to accomplish this goal, and the early return approach outlined below is one of them.

reduceVote(index:number) {
  if(this.quotes[index].downvotes === 0)
    return;
  this.quotes[index].downvotes -= 1;
}

Answer №3

Approach 1:

Implementing it using pointer-events with the help of ngClass.

In your .html file

<li *ngFor = 'let quote of quotes; let i = index' quotes>
 <div class="col-md-6 downvotes">
  <img src="assets/down-arrow.png" alt="" [ngClass]="{quotes[index]<=0?'click-disabled':'click-enabled'}" (click)="downVote(i)">
  <span >{{quote.downvotes}}</span>
 </div>
</li>

In style.css file

.click-disabled{
  cursor: not-allowed;
  pointer-events: none;
}
.click-enabled{
  pointer-events: auto;
  cursor: pointer;
}

Approach 2:

Checking for conditions upon click and performing actions accordingly.

downVote(index:number) {
  if(this.quotes[index].downvotes === 0)
    return;
  --this.quotes[index].downvotes;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

Using Angular 4 with Firebase to display nested objects within an object

My Firebase data: { "hotel" : { "-Kjgyamcup6ULm0Awa-1" : { "complete" : "true", "images" : { "-Kjgyb6A2gRiDhwaWx-V" : { "name" : "2.jpg", "url" : "https://firebasestorage.googleapi ...

Navigating the complications of handling double submissions in Angular2

Whenever I rapidly click on the submit button, the form ends up being submitted multiple times. My initial solution was to use the disabled attribute, but I find myself needing the disableButton variable in every form instance like this: @Component({ ...

Combining cells for certain entries in an Angular data table

Just starting to learn angular, and here's the scenario I'm dealing with: I have a table consisting of 10 columns. Let's say column 4 contains different status categories like children, teen, young, adult, and senior. When displaying all ...

Accessing Component Instance in Ionic 3 Modal Controller

I am currently displaying a Component called EventFeedbackComponent through ModalController. I want to subscribe to a Subject within the EventFeedbackComponent. How can I access the component instance in order to achieve this? This is what my code looks l ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

Angular 2 (stable) is experiencing issues when attempting to route with an outlet and a non-empty path

A route in Angular2 uses the following router path: { path: 'lefttoggle', redirectTo: 'lefttoggle', pathMatch: 'full', outlet: 'lefttoggle_name'}, An exception is being thrown when this route is accessed. Edit: ...

Is there a way to cancel or undo a transaction in the middle of using the PayPal JavaScript SDK?

As a newcomer to Angular, I am working on integrating PayPal as a payment gateway. However, I am unsure of the correct procedure to follow. paypal .Buttons({ createOrder: (data, actions) => { return actions.order.create({ purchase_ ...

Unleashing the full power of TypeScript: Harnessing Array.prototype.reduce with Generics

Attempting to standardize data using Array.prototype.reduce. Puzzled by how I can bypass "type-checking" in the reduce function. My interfaces: interface Dict<T> { [key:string]: T; } interface InnerData { id: string; value: number; } inter ...

Transforming the string attribute of an object within a JavaScript array through mapping

Here is an array of objects: { "attr1": 123, "attr2": "a.end", }, { "attr1": 123, "attr2": "b.start", } The task is to remove the first part of the attr2 string up to and including the '.& ...

Addressing Uninitialized Variable Concerns Within TypeScript's strictNullChecks Feature

Here is an example of some TypeScript code: let foo: string; function test() { console.log(foo.trim()) } test() I have enabled the strictNullChecks option in TSConfig. I was expecting the compiler to raise the error 'foo' is possibly 'und ...

Exploring the Functionality of Observables and HTTP Requests in Angular

When I use the http get method in Angular, it returns an observable. To test this, I created a local server that serves up a 50 MB JSON file containing all employee data. import { Injectable } from "@angular/core"; import { Http } from "@angular/http"; im ...

Obtain keys from an object implemented with an interface in TypeScript

Is it possible to retrieve the actual keys of an object when utilizing an interface to define the object? For example: interface IPerson { name: string; } interface IAddress { [key: string]: IPerson; } const personInAddressObj: IAddress= { so ...

"Is it possible to differentiate between a variable that is BehaviorSubject and one that is not

I am dealing with a variable that can be of type Date or BehaviorSubject<Date | null>. My concern is figuring out how to determine whether the variable is a BehaviorSubject or not. Can you help me with this? ...

Issue with Typescript npm script including compilation and nodemon issue

After exploring various SO links, I tried to find a way to simultaneously run both tsc -w and nodemon app.js using a single command. The link I referred to is: How do I execute typescript watch and running server at the same time? Working on a node.js pr ...

Troubleshooting a 400 error when trying to authenticate with Firebase using AngularFire2

Authentication through Google has been enabled in the console: https://i.sstatic.net/Kkdh3.png Here is the login code: import { Component, OnInit } from '@angular/core'; import { AngularFire, AuthProviders } from 'angularfire2'; @Com ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

When invoking a callback function that includes a conditional type, TypeScript mandates the inclusion of a parameter that intersects multiple types

There is a function that requires specific arguments, including a callback function that takes an object or an array of objects based on an isArray parameter. I am attempting to create a new feature. type Option = { name: string value: string } type ...