Search code examples
angulartypescript

How to add if condition within another if condition


I am new to Angular 17 and i have basis question. I declared interface like below:

.ts

export interface Monthly {
  label?: string;
  description?: string;  
  quantity?: number;
}

Then i declared Monthly interface within class like below:

monthly: Monthly = {
    label: 'Test label',
    description: "Test desc",
    quantity: 3,
  }

Quantity value is hard coded here but it can change. Below is const i declared and setting its value. How can i add check on this.monthly.quantity so that it concatenated with this.monthly.label if its value is greater than 1 but doesn't appear if its value is less than 2.

const desc = this.monthly?.label ? `${this.monthly.quantity} ${this.monthly.label}` : ` No label`;

Solution

  • const desc = this.monthly?.label
        ? (this.monthly.quantity && this.monthly.quantity > 1)
            ?`${this.monthly.quantity} ${this.monthly.label}`
            : this.monthly.label
        : ` No label`;