Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8.

The employee-list component is responsible for presenting data in a table format.

Within the employee-list.component.ts file, I have defined:

import { Component } from '@angular/core';
import { Employee } from '../../models/empModel';
import * as data from '../../data/employees';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css'],
})
export class EmployeeListComponent {
  public displayMode: String = 'grid';
  public deptno: number = -1;
  public empsArray: Employee[] = data.employees;

  public removeEmployee(empno: number) {
    this.empsArray = this.empsArray.filter((item) => item.empno != empno);
  }

  public filterByDepartment(num: number) {
    this.deptno = num;
  }

  public setDisplayMode(mode: String) {
    this.displayMode = mode;
}
}

In the view:

<div class="table-responsive">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Full Name</th>
          <th>Job</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let employee of empsArray | filter: deptno">
          <app-employee-table-item
            [employee]="employee"
          ></app-employee-table-item>
        </tr>
      </tbody>
    </table>
  </div>
  

Each row in the table is handled by a child component called employee-table-item:

import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Employee } from '../../models/empModel';

@Component({
  selector: 'app-employee-table-item',
  templateUrl: './employee-table-item.component.html',
  styleUrls: ['./employee-table-item.component.css'],
})
export class EmployeeTableItemComponent {
  @Input() employee: Employee;
}

The Issue

The table layout is incorrect because each row is enclosed in an unnecessary

<app-employee-table-item></app-employee-table-item>
element.

I aim to display the content of every table row directly within the <tr> tag while preserving the template in a separate HTML file.

Query

What is the most effective approach to displaying the contents of each table row directly inside the <tr> tag?

Answer №1

To resolve the issue, consider utilizing your component as a directive. This approach is frequently employed in situations such as yours.

app-employee-table-item:

@Component({
  selector: '[appEmployeeTableItem],app-employee-table-item',
  templateUrl: './employee-table-item.component.html',
  styleUrls: ['./employee-table-item.component.css'],
})
export class EmployeeTableItemComponent {
  @Input('appEmployeeTableItem') employee: Employee;
}

In EmployeeList.html :

<tbody>
    <tr
      *ngFor="let employee of empsArray | filter: deptno"
      [appEmployeeTableItem]="employee"
    ></tr>
  </tbody>

Answer №2

To solve this issue, a recommended approach is to transition from utilizing a tag selector to employing an attribute value selector.

In the file employee-list.component.html, make the following replacement:

<tr *ngFor="let employee of empsArray | filter: deptno">
    <app-employee-table-item
        [employee]="employee"
    ></app-employee-table-item>
</tr>

with this:

<tr
    data-selector="app-employee-table-item"
    *ngFor="let employee of empsArray | filter: deptno"
    [employee]="employee"
></tr>

In the file employee-table-item.component.ts, update the selector to:

selector: '[data-selector=app-employee-table-item]',

Subsequently, instead of searching for <app-employee-table-item\> HTML elements, Angular will seek out any HTML elements containing an attribute named data-selector with a value of app-employee-table-item and substitute that element with your template.

Your modified Stackblitz can be accessed through this link: https://stackblitz.com/edit/angular-modal-bootstrap-ke3bbc?file=src%2Fapp%2Fcomponents%2Femployee-list%2Femployee-list.component.html

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

I am attempting to code a program but it keeps displaying errors

What is hierarchical inheritance in AngularJS? I have been attempting to implement it, but I keep encountering errors. import {SecondcomponentComponent} from './secondcomponent/secondcomponent.Component'; import {thirdcomponentcomponent} from & ...

Consumer using ActiveMQ-Stomp is not receiving any messages

I attempted to create a JavaScript code for an ActiveMQ subscriber that would subscribe to a specific topic, but unfortunately I am not receiving any messages after establishing the connection. The topic that needs to be subscribed to is COO.2552270450083 ...

Opt for res.render() over res.send() when developing in Node.js

I recently developed an image uploader for ckeditor. After uploading a file, I need to send back an html file that includes the name of the image to the client. Check out the code snippet below: router.post('/upload', function (req, res, next) ...

Configuring Axios header in Java backend based on the value stored in the express session

I am currently working on a frontend app using node.js express for server-side rendering. This app calls java backend endpoints and I use Axios to make the requests. A specific header named "agent-id" needs to be set in every request that is sent from expr ...

Vue: utilizing shared methods in a JavaScript file

Currently, I am building a multipage website using Vue and I find myself needing the same methods for different views quite often. I came across a suggestion to use a shared .js file to achieve this. It works perfectly when my "test method" downloadModel i ...

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Insert an HTML tag into JSLint

Is there a way to include an HTML tag in JSLint's list of recognized tags? I'm encountering some errors with the following message: JSLint: Unrecognized tag 'foo'. How can I make the foo tag recognized by JSLint as a valid HTML tag? ...

Setting the chosen value within a nested ng-repeat loop

I'm struggling with correctly setting up the select boxes in a form that uses nested ng-repeats. The form has parent table rows generated with an ng-repeat, and each row contains a select box that is linked to an attribute in the parent row. The optio ...

Prevent Dehydration issue while using context values in Next Js

Every time I log in with a user, update a context value, and re-render some components, I keep encountering a Hydration error in Next Js. The issue seems to be specifically with my NavBar component which is rendered using react-bootstrap. The code snippet ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...

What could be causing appendChild to malfunction?

I'm having an issue trying to create three elements (parent and one child) where the third element, an <a> tag, is not appending to modalChild even though it's being created correctly. modal = document.createElem ...

Using Angular 2 to assign unique ids to checkbox values

Is there a way to retrieve the value of a checkbox in Angular 2 without needing an additional Boolean variable? I am trying to toggle the enabled/disabled state of an input field based on the selection of a checkbox. While I know this can be accomplished ...

Using AngularJS to interact with neighboring DOM elements

Imagine a scenario where there is a div containing 5 img elements. When one of these img elements is hovered over, the goal is to change the class of all the elements on its left side. <div id="stars"> <img src="star.png" data-rating="1" ng- ...

Self-referencing object identifier

Having trouble articulating this question, but I'm attempting to develop a JavaScript object that manages an array of images for reordering and moving purposes. function imgHandler(divname) { this.imgDiv = divname; this.img = Array("bigoldliz ...

Is there a way to pre-load images from component B within component A using Vue?

In a scenario where I have two Vue files, A.vue and B.vue, the issue arises when navigating from A to B. B contains numerous images fetched from Firebase realtime database, resulting in slow loading times upon first visit. To address this, I aim to preload ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

Is it feasible for a JavaScript function to receive the innerHTML of the element from which it is invoked as an argument?

Is there a way to bind a function that takes a String as a parameter to a button so that it is called onclick and takes the innerHTML of the element as a parameter, without assigning the button an id or using queryselector? <button onclick="myFunct ...

Maintain the nullability of object fields when casting

I have been working on a type called DateToNumber that converts all the Date properties of an object to number. Here is what I have come up with so far: type LiteralDateToNumber<T> = T extends Date ? number : T extends Date | null ? number | nu ...

I'm unable to resolve the issue regarding the message "Property or method is not defined on the instance but referenced during render."

I have a good grasp on what the issue is (the inputs I'm trying to v-model aren't declared), but for some reason, I can't resolve it (or figure out how to) even after studying other posts with the same problem. After comparing my code with ...

What is the best way to use element.appendChild to generate a link?

I am currently utilizing the following snippet of Javascript to extract information from the current webpage using a browser extension. I have only included a portion of the code that is relevant, as the full script is quite lengthy. The code works perfect ...