Issues encountered when trying to manipulate the Angular dom

Currently, I have an array of check boxes set up in the following manner:

<div *ngFor="let order of orders; let i = index">
    <input type="checkbox" id="{{orders[i].name}}_i">{{orders[i].name}}
  </div>

Let's say the check boxes are labeled as order1, order2, and so on.

My goal is to be able to change the status of these check boxes (check/unchecked) based on their IDs or through some other method, like this:

document.getElementById("order1").checked = true;

I have attempted this approach, but encountered errors and it did not work as expected.

During my research, I came across a potential solution using @ViewChild. However, this would require me to predefine the IDs, whereas in my case, the ID can vary. Can you suggest an alternative mechanism for achieving this?

Answer №1

If you're working within an Angular and TypeScript environment, JavaScript may not be necessary. Utilize Angular's Two-Way binding feature to accomplish your goals efficiently.

Incorporate a checked property into your "order" model and bind this property to the checkbox input using ngModel.

order.ts

export class Order {
  public name: string;
  public checked: boolean;
  ...
}

component.ts

@Component(...)
export class MyComponent {
  public orders: Array<Order>; // Initialize with ngOnInit hook or any other way.
}

component.html

<div *ngFor="let order of orders; let i = index">
    <input type="checkbox" [(ngModel)]="order.checked">{{order.name}}
</div>

Remember, you can access the current object directly through the order variable rather than using orders[i]. For more details, visit Angular's official documentation: https://angular.io/guide/displaying-data#showing-an-array-property-with-ngfor

To update the checked state of your items, simply modify the checked value of any Order object, and it will automatically reflect on your interface:

@Component(...)
export class MyComponent {
  public orders: Array<Order>; 

  public checkFirstOrder(): void {
    this.orders[0].checked = true;
  }
}

Hopefully, this information proves helpful for you.

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

Definition of Jasmine custom matcher type

I have been working on adding typescript definitions to a custom jasmine matcher library. Initially, I successfully added matchers for the generic type T. Now, my goal is to specifically add matchers for DOM elements. While exploring the jasmine type def ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Editing the dimensions of the input in Bootstrap 4

Is there a way to adjust the width of the input and select elements? I want the input element to take up more space while the select element occupies less space. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel=" ...

What are some strategies for enhancing the efficiency of asynchronous data retrieval and caching?

I'm using this code to retrieve data asynchronously and store it in a cache for performance optimization: let cache = {} const optimizedFetch = async (url) => { if (url in cache) { // return cached result if available console.lo ...

Utilize Firebase to perform a case-insensitive query

Our Angular/Ionic app requires users to provide their email during registration, which is then saved in the User collection. We also validate if the email is already in use with a query like this: firestore .collection("User") .where("email", "==", ...

Learn the technique of storing a sequence of functions within a variable using jQuery

For instance, I am looking to assign a sequential process to multiple variables and utilize them in various scenarios. var disable_btn = true; var button_me = $('#contents.getsamplekit .sample-form .form #submit-btn-freeSample-me'); var button_d ...

Take away the focus from Bootstrap 5 toggle button once it has been clicked

Working with the Bootstrap 5 Toggle Button in Outline Style to enhance visual emphasis hasn't provided the ideal user experience I was hoping for. (Refer to https://getbootstrap.com/docs/5.0/forms/checks-radios/#outlined-styles) The toggle functional ...

Guide to enabling gzip compression for an Angular 6 application running on asp.net core 2.1 and hosted on Azure App Services

Is there a way to implement gzip compression for an Angular 6 asp .net core 2.1 application hosted on Azure App Services? Should I address this in the codebase or can it be configured directly within Azure App Services? ...

Setting up module aliases in a monorepo initiated with Turborepo: a step-by-step guide

Currently working on migrating multiple repositories to the monorepo architecture using a POC bootstrapped with Turborepo. Facing an issue with misconfigured ts module aliasing. Have a single ui package where I am attempting to export a button component fr ...

activating a button following the selection of a checkbox

My code includes a submit button that is currently disabled. I am looking to enable it when the user clicks on the "I agree" checkbox using jQuery. Can someone assist me with this? My code is written in HTML, JavaScript, and jQuery. <input id="agree" ...

Self-reference within a JavaScript object involves creating a property that points

Can you reference another part of a JSON object within the same JSON object? In the code snippet below, there is an object that refers to the "home" object within the "MapParameters" object. { "parameters": { "data": { "URL": "http://SC.json ...

"Learn the steps to include a success message in an HTTP POST response once a button has been

Currently, I am utilizing nodemailer along with express... I aim to incorporate a text message and loading indicator on the front-end to indicate whether the form submission is in progress or not. .ts deliverEmail(value) { console.log('em ...

Steps to have index.html display when running the build command in a Svelte project:

Greetings everyone, I'm brand new to using Svelte and have a question that's been on my mind. I recently developed a small app in Svelte that works perfectly fine during development. However, when I run npm run build for production, the output ...

Issues with extensions during the Angular 9 Ivy compilation process

Good day! After upgrading a v8 project to v9, I encountered some errors related to extensions in the compiler. These errors are not present in another project that I also recently upgraded. The extensions, which are basic for constructors and prototypes, ...

Adjust the iframe height when using slidetoggle

I currently have a menu positioned in the center of the screen, set to "show" by default. Beneath this menu, there is an iframe filling up the remaining space: <script type="text/javascript> $(document).ready(function() { var main_height = ($(d ...

Eliminating data type from union in Typescript

I have a specific type that I collect from various other types: type CustomType = { id: string; foo: (string | Type1)[]; bar: (string | Type2)[]; baz: string | Type3 | null; description: string | null; } I am interested in refining thi ...

What is the best way to convert the value of "range" to floating point numbers in JavaScript?

Why is it that when I input a float number, like "3.4567890", as the value in an input field, it automatically gets converted to type 'int'? This conversion is not desired, as I want the value to remain as a 'number' or 'float&apos ...

Looking to decrease Cumulative Layout Shift (CLS) on the NextJS website for enhanced performance

I have chosen to use NextJS with Mantine for my website development. Utilizing createStyles, I have added custom stylings and incorporated various mantine components into the design. After deploying the site on Vercel, I discovered that all performance me ...

Save the XML file and input the value (XMLHttpRequest is unable to load the file) - On the Client Side

Important Note: All operations are performed client-side I am attempting to upload an XML file and display the values in a text input field. I have been using AJAX to perform this post operation. While it works smoothly on Firefox, there seems to be a pro ...