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

Leveraging Web Services in Outlook Mail Add-On

I am facing a challenge with an Outlook Mail Add-In that I need assistance with. Using an Office 365 developer account, the Mail Add-In displays online in a browser as shown in this screenshot: https://i.stack.imgur.com/ZQ9qt.png My objective is to trigge ...

In Laravel, a post request can pass a class with a property that is of a different class type

In my Laravel controller, I have the following function: public function save(Request $request, ClientOrderDTO $clientOrderDTO){ } The definition of the ClientOrderDTO used above is as follows: use App\DTO\ClientDTO; class ClientOrderD ...

Utilizing Datepicker in CodeIgniter to Implement Server-Side Date Range Filtering with Datatables

Seeking urgent assistance. After weeks of trying various codes sourced online, I am still unable to implement Datatables serverside date range functionality using Codeigniter with the date picker. Whenever the selected dates differ, I end up with a range s ...

Place in the Middle of a Bootstrap Container

Struggling with aligning the elements of a Bootstrap well in the center? The badge is off to the side instead of below the arrows, and the vote buttons are not centered within the well. Check out the code snippet below: HTML: <div class="col-md-1 ...

Surround the image with horizontal links on each side

I am attempting to design a horizontal unordered list with an image positioned in the center of it. I am facing the challenge of not being able to insert the image directly within the unordered list. Is there a way to align the image in the center while ha ...

Unable to apply inset box-shadow to image

I've added a box-shadow to my image. box-shadow: 0 0 10px RED inset However, the shadow is not showing up on the image. When I use Firebug to change the image path, I can see that the shadow is behind the image. How can I apply the shadow directly ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

Tips for adjusting the content direction of a Popover

I am currently working on a component that includes the following code: import { Popover, PopoverTrigger, PopoverContent, PopoverBody, Portal, Button, } from "@chakra-ui/react"; import { ReactNode } from "react"; import { Co ...

Tips for effectively sizing a logo within a Bootstrap navbar

<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

Guide to verify the user selection within a select form

Here is a form with a select field: <form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt"> <select style="background: transparent; border-bottom:5px;" name="subname" class="required"> ...

What is the best way to use jQuery to adjust the size of a slider image based on a percentage of the browser window

I've been searching all over for a solution to this issue, but so far I haven't had any luck. Basically, I have an image that is 1800 pixels wide by 500 pixels high. I need this image to adapt to all screen resolutions. Instead of having a fixed ...

Passing arguments from nodes in Angular 2

I am looking to pass a parameter from a node, rather than a property. Here is an example of what I want: <!-- I want to use this: --> <navbar-comp> <items> <item label="Page 1" path="/page1" /> <item label="Page 2" pat ...

Issues with the parallax zooming out effect

Delving into the world of parallax effects, I'm on a quest to achieve a captivating zoom-out effect while scrolling. However, I'm encountering an issue where the image shrinks beyond the browser width and the div's height. In the example pr ...

What is the best way to dynamically generate and update the content of a select input in an Angular form using reactive programming techniques?

I have successfully developed an Angular reactive form that includes a select field populated dynamically with values retrieved from an API call. In addition, I have managed to patch the form fields with the necessary data. My current challenge is to dyn ...

Access error message through ajaxError binding

I've reviewed various similar inquiries on Stack Overflow, but none address the issue I'm encountering. Within my global.js file, this is what I have: $(document).ready(function () { $(document).ajaxSend(function () { ShowLoading(); }); ...

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

ways to invoke javascript function on body loading

I'm struggling to invoke a JavaScript function when the body loads. Currently, I have the function call on a button but cannot get it to work when added to the body load event. HTML: <body onload="bodyload();"> JavaScript: function bodyload( ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

Having trouble getting my parallax slideshow to work with jquery preventDefault

-UPDATE- After countless hours of online courses, tutorials, and programming, I finally completed my website! Check it out here: The site is almost where I want it to be, but there are a few remaining challenges: 1) AJAX: I'm struggling to get the ...