modify text label once checkbox is selected in angular

After following the steps in this tutorial on dynamic checkboxes in Angular, I successfully created dynamic checkboxes. Now, I'm facing an issue where I need to change the text label only after a checkbox is checked. I haven't been able to figure out how to make this change occur only on the selected index without affecting all other text labels. Here's what I've attempted so far: demo,

This is my desired outcome:

Before checked:

  • select (ticked checkbox)
  • select
  • select
  • select

After checked:

  • selected (change text label)
  • select
  • select
  • select

Answer №1

Changing the labels text using a single variable called marked is not the best approach.

A better way to do this would be to use the value of each control as shown in the code snippet below.

<span *ngIf="order.value">
  {{orders[i].text2}}
</span>
<span *ngIf="!order.value">
  {{orders[i].text1}}
</span>

Answer №2

To display conditional text based on a checkbox selection, you can use the (change) event to trigger an alert of the checked value.

Demo Link

HTML File

<label *ngFor="let item of items">
  <input type="checkbox" (change)="onChecked(item)"/>
    {{ item.name }}
    <span *ngIf="(item.checked)">
      Selected
    </span>
</label>

.ts file

import { Component } from '@angular/core';

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

  items = [
    { id: 100, name: 'item 1' },
    { id: 200, name: 'item 2' },
    { id: 300, name: 'item 3' },
    { id: 400, name: 'item 4' }
  ];

  onChecked(item) {
    item.checked = !item.checked;
  }
}

Answer №3

Here is some potentially helpful code:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { of } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  form: FormGroup;
  orders = [];
  marked = false;

    constructor(private formBuilder: FormBuilder) {

    this.form = this.formBuilder.group({
      orders: new FormArray([], minSelectedCheckboxes(1))
    });

    // async orders
    of(this.getOrders()).subscribe(orders => {
      this.orders = orders;
      this.addCheckboxes();
    });

    // synchronous orders
    // this.orders = this.getOrders();
    // this.addCheckboxes();
  }

   private addCheckboxes() {
    this.orders.map((o, i) => {
      const control = new FormControl(i === 0); // if first item set to true, else false
      (this.form.controls.orders as FormArray).push(control);
    });
  }

  getOrders() {
    return [
      { id: 100, name: 'order 1', text1: 'select', text2: 'selected' },
      { id: 200, name: 'order 2', text1: 'select', text2: 'selected' },
      { id: 300, name: 'order 3', text1: 'select', text2: 'selected' },
      { id: 400, name: 'order 4', text1: 'select', text2: 'selected' }
    ];
  }

    toggleVisibility(e, i) {

      console.log(e,i);
      console.log(this.orders[i]);
      console.log(this.form.controls.orders['controls'].value);

    if(this.form.controls.orders['controls'][i].value)
    {
      this.orders[i].text1 = 'justSelected';
    }else{
      this.orders[i].text1 = 'UnSelected';
    }

    console.log(this.form.controls.orders['controls']);
    console.log(i);
  }
}

function minSelectedCheckboxes(min = 1) {
  const validator: ValidatorFn = (formArray: FormArray) => {
    const totalSelected = formArray.controls
      .map(control => control.value)
      .reduce((prev, next) => next ? prev + next : prev, 0);

    return totalSelected >= min ? null : { required: true };
  };

  return validator;
}

Update on the HTML part:

<hello name="{{ name }}"></hello>

<form [formGroup]="form" (ngSubmit)="submit()">
  <label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
    <input type="checkbox" [formControlName]="i"
    (change)="toggleVisibility($event, i)">
      <span >
       {{orders[i].text1}}
      </span>

  </label>

  <br>
  <button [disabled]="!form.valid">submit</button>
</form>

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

Is a no-cache directive required in Angular index.html?

Is there a way to prevent index.html from caching and instead have it constantly reloaded? I would prefer not to have cache enabled. Any suggestions on how I can achieve this? Thank you! ...

tips on waiting for the outcome of an http request (synchronous http request, utilizing http request as a promise)

My TypeScript service loads base data through HTTP requests from a server. The requests are for various data, arranged in order from independent data to data that depends on other data. Due to the asynchronous nature of HTTP requests, there is no guarant ...

Typescript and Apollo Client return types intertwined

My goal is to create a simple function within a class that generates an Apollo Client. Below is the code I have implemented: import appConfig from 'config/app-config'; import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/clie ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Unable to bring in an exported class from a TypeScript file

I have a TypeScript file named foo.ts that contains an exported class called "Foo" export default class Foo{ } I am attempting to import this class into another file within the same directory import {Foo} from './foo'; However, I am encounter ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

choose a distinct value for every record in the table

My goal is to only change the admin status for the selected row, as shown in the images and code snippets below. When selecting 'in-progress' for the first row, I want it to update only that row's status without affecting the others. <td ...

Using the amDateFormat pipe in Ionic 3's Lazy Loading feature

Currently, I am using Ionic3 and working on transitioning to Lazy Loading to enhance the startup performance. Since converting my ChatsPage to lazy loading, I have encountered an issue with pipes. The error message points to a specific line in my chats.ht ...

Handling onChange events for several typescript <Select> elements

As a non-TS developer, I'm delving into the realm of multiple selects and dropdown menus with Material-UI's select component. Progressing from a basic setup, I successfully implemented a single select but now face a challenge in adding another dr ...

No contains operator found in Material UI Datagrid

While working on a project, I utilized Material UI's datagrid and successfully implemented filters such as contains and isEmpty. However, I am struggling to find information on how to create a notContains filter. Does Material UI natively support this ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

Avoiding redundancy when importing identical CSS file in multiple documents

I'm currently working on an Angular project that utilizes Sass for CSS processing, but I'm considering integrating Tailwind CSS. I'm interested in importing Tailwind into different component Sass files to build upon them, but I've notic ...

Issue with Ionic 4 IOS deeplinks: Instead of opening in the app, they redirect to the browser

After working diligently to establish deeplinks for my Ionic 4 iOS application, I meticulously followed a series of steps to achieve this goal: I uploaded an Apple site association file to the web version of the app, ensuring the utilization of the prec ...

Guide to comparing two TSX elements in a React + TSX environment

I am facing difficulties in comparing two React TSX elements. Despite being new to both React and TSX, I have tried copying and pasting the exact elements for comparison but it doesn't seem to work. Can you guide me on what might be causing this issue ...

Angular application integration with three.js OrthographicTrackballControls

Has anyone successfully integrated the OrthographicTrackballControls from three.js with Angular 4? I attempted to do so by running: npm install --save three-orthographic-trackball-controls Then in my component: import { OrthographicTrackballControls } f ...

Exploring the integration of traditional service methodologies into modern Angular applications

I am tasked with converting various types of services like SOAP-based services, WCF XML services, and web services that are currently running in a Silverlight app. For this conversion, we plan to use Angular as the front end while keeping the server side u ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

There appears to be no overload that aligns with this call using styled components (index.d.ts(2187, 9))

Trying to create an Input component using styled components that accepts props but encountering an error when using the onChange prop - No overload matches this call. It seems like there might be an issue with my types, but even after extensive research, I ...

Extract array values from object properties

Is there a way to destructure an object and assign its properties into an array instead of as variables? For instance: const obj = { a: 1, b: 2 }; const { a, b } = obj; const arr = [a, b]; The above method works fine, but it involves redefining the vari ...

Exploring the Basics of Angular's @HostBinding FeatureIn this article,

Understanding the Angular @HostBinding concept has been a challenge for me. Although my book is great, this particular topic isn't explained very clearly. Take a look at the code snippet below: @Component({ selector: 'app-test-component', ...