Unable to apply styling to table cells that are dynamically added using JQuery within an Angular

Currently working on setting up a form using Angular. Within the hotel.view.html file, there is a table that looks like this:

<table id="rooms">
   <tr>
     <td>Room Type</td><td>Beds</td><td>Q.ty</td>
   </tr>
   <tr>
     <td><input [(ngModel)]="HotelModel.rooms[0].type" name="type" type="text"></td>
     <td><input [(ngModel)]="HotelModel.rooms[0].beds" name="beds" type="number" class="smallField"></td>
     <td><input [(ngModel)]="HotelModel.rooms[0].qty" name="qty" type="number" class="smallField"></td>
   </tr>      
 </table>

In the hotel.component.css file, there are styles for two classes: .smallField and .bigField.

.smallField {
    display: inline-block; 
    width: 50px;
}
            
.bigField {
    display: inline-block; 
    width: 170px;
}

The "display: inline-block;" property was added to accommodate DIV elements initially, but now it's not necessary.

The table rows with fields are displayed correctly. Now, I want to add a new row when a button is pressed. Here is how I do it:

$("#addRoom").on("click", function() {
        $('#rooms tr:last').after(
          '<tr><td><input [(ngModel)]="HotelModel.rooms[' + rm + '].type" name="type" type="text"></td>' + 
              '<td><input [(ngModel)]="HotelModel.rooms[' + rm + '].beds" name="beds" type="number" class="smallField"></td>' + 
              '<td><input [(ngModel)]="HotelModel.rooms[' + rm + '].qty" name="qty" type="number" class="smallField"></td></tr>');
          rm = rm + 1;
        });

The newly added row appears correctly, but the fields don't inherit the "smallField" class, resulting in an inconsistent look:

https://i.stack.imgur.com/NebIa.png

Any suggestions on how to style these fields properly? Thank you!

Answer №1

It is crucial to avoid using jQuery in an Angular project, as mentioned in a previous comment. Achieving what you are attempting here is quite simple and can be done solely with Angular.

If your data is stored in an array, all you need to do is add a new item to that array. Angular will automatically recognize the change, making it much more straightforward than integrating raw HTML using a separate library that Angular must somehow interpret.

To display the array, utilize an Angular ngFor loop. By clicking the button, a new item will be added to the array, simplifying the process.

<table id="rooms">
  <thead>
    <tr>
      <th>Room Type</th>
      <th>Beds</th>
      <th>Q.ty</th>
    </tr>
  <thead>
  <tbody>
    <tr *ngFor="let room of roomsList">
      <td><input [(ngModel)]="room.type" name="type" type="text"></td>
      <td><input [(ngModel)]="room.beds" name="beds" type="number" class="smallField"></td>
      <td><input [(ngModel)]="room.qty" name="qty" type="number" class="smallField"></td>
    </tr>
  </tbody>  
</table>

<button type="button" (click)="onAddRoomType()">Add Room Type</button>
roomsList = [...HotelModel.rooms]; //creates a copy of the array and stores it in this new array

onAddRoomType() {
  this.roomsList.push({ type: '', beds: 0, qty: 0 });
}

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

Fetching data from Page 1 and passing it to Page 2 using Javascript

I'm currently experiencing an issue with my AJAX function where it needs to transfer a value from page 1 to page 2 for storage. Let's start with the AJAX function on page one: top.location.href = 'http://www.something.com/redirect.php?emai ...

What could be causing my click event to fail to register after sorting a WebGrid with a click?

Running into an issue with my webgrid and search button. It works perfectly if I search first, updating the grid with results. But when I click on a header to sort the grid, the search button stops working. Can't seem to figure out how to solve this d ...

Preventing event propagation in jQuery's click handler

Is it possible to prevent the propagation of a click event on a dynamically created div within its parent div? HTML <div id = "parent"> Some Stuff </div> Jquery $('#parent').click(function(){ $(this).append('<div class = ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Extract the URL parameter and eliminate all characters following the final forward slash

Here is the URL of my website: example http://mypage.com/en/?site=main. Following this is a combination of JavaScript and PHP code that parses the data on the site. I am now looking for a piece of code that can dynamically change the URL displayed in the ...

Server-side execution of jQuery and HTML components

In the user control (header), there is a div containing different sub divs. One of these sub divs includes user options, displaying the username of the logged-in user and links for logout, settings, etc. This "user_options" div is positioned absolutely wit ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...

CSS showcase of a minimalist image gallery

I have designed a simple image gallery using the following CSS: .product_container { width:100%; display:block; } .product_images { width:45%; display:inline-block; border:1px solid black; } .product_images .large { } .product_images ...

Enable a button or class to dynamically alter its color

Hi there! I'm new to coding and just started learning HTML and CSS. My question is: How can I change the color of buttons once they are clicked? <div class="icon-bar"> <a href="#"><i class="fa fa-search" ...

What are the best strategies for ensuring this website is fully optimized for all devices

Hi there, I've been struggling to make the header on my website responsive, but it doesn't appear to be functioning properly. Any assistance would be greatly appreciated. <!DOCTYPE html> <html lang="en"> <head> <meta name="v ...

Issue with Navigation menu dropdown not functioning properly on Angular version 12 with Bootstrap 5

I am attempting to integrate bootstrap with Angular through a CDN. Below is the content of my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Laboratorio Sigma< ...

Angular 5 - Keeping track of variable updates

I've searched various topics on this issue, but none seem to address my specific problem. I need a way to detect changes in the properties of a component without having to convert the variable into an array or iterable. I tried using Subject, but coul ...

Ensure that radio buttons are positioned next to their respective labels on separate lines

My HTML form is structured with sections as described below: I prefer having the labels inline to prevent the section from being excessively tall, but I'm facing an issue where the radio buttons are not staying aligned with their respective labels. ...

Identifying added elements that respond to link hover effects

I've been working on a project where I'm trying to replace the default browser cursor with an SVG one using jQuery. Everything seems to be working smoothly, except for changing the cursor when it hovers over links - nothing I've tried so far ...

I'm having trouble with my dropdown navigation menus - they keep popping back up and I can't seem to access

My website is currently in development and can be accessed at: The top navigation bar on the homepage functions properly across all browsers. However, there are three sections with dropdown submenus - About Us, Training, and Careers. These dropdown submen ...

What are some effective CSS styles that can be used to illustrate the concept of "loading . . ."?

I've been leveraging the power of blockUI successfully, but now I'm faced with the challenge of dynamically loading a table row. My research indicates that blockUI may not be compatible with HTML table rows. My idea is to use: jquery.AddClass(" ...

Utilizing Angular to upload videos

I'm having an issue while attempting to upload a video using Angular and send it to a PHP backend server. Currently, I am working with Angular 6 and have utilized ng2-file-upload. While this method works well for images, when I attempt to send a vide ...

Setting a custom background image in HTML using the designated file PATH

My current issue involves the inability to set my background photo using a CSS file. I am utilizing NetBeans for this project. Inside a folder named css, there is a file called global.css which contains the following code: body{ background-image: url ...

What is the method for aligning a glyph vertically?

Can anyone help with aligning the glyph vertically to the text? Currently, it seems more like it's attached to the bottom. Here is an example: <a href="#">Zoom</a> a { font-family: 'Open Sans', sans-serif; font-weight: ...