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

`As the input value for these methods`

I am encountering an issue when trying to pass in this.value as a method argument. The field values are all strings and the constructor arguments are also all strings, so I don't understand why it's not working. When I attempt to pass in this.cla ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further d ...

By default, the ejs-datetimepicker in @syncfusion/ej2-angular-calendars will have an empty input field

I incorporated a datetime picker from @syncfusion/ej2-angular-calendars into my project. However, I noticed that the datetime picker displays the current date and time by default in its input field. Instead, I would like the input field to be empty when ...

Ways to eliminate the unusual dashed space in ReactJS using Bootstrap

While developing an app with NextJS and Bootstrap, I noticed a strange dashed gap at the top of the screen in the elements tab. Despite checking for margin or padding-top properties on any element, there doesn't seem to be a clear cause for this issue ...

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

The consistent failure of the 201 status node express API is causing major

I am currently working on creating an API using Express. However, when I receive a response from the server, it shows '201 created'. The issue arises when I attempt to make an HTTP request through promises and encounter a false interpretation of ...

Saving URLSearchParams to a file using javascript

I am currently implementing jstree and I need to be able to click on a file within the tree structure in order to display a PDF file. Below is the relevant code snippet: $(function () { $('#tree').jstree({ 'core' : { ...

How many intricate objects are instantiated in memory when running the code snippet provided above?

When looking at the given code, how many complex objects can we identify in memory? function Foo() { this.one = function() { return "one"; } } var f = new Foo(); Foo.two = function() { return "two"; }; Here's what I see: The Foo co ...

What's the best way to replicate a specific effect across multiple fields using just a single eye button?

Hey everyone, I've been experimenting with creating an eye button effect. I was able to implement one with the following code: const [password, setPassword] = useState('') const [show, setShow] = useState(false) <RecoveryGroup> ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

Displaying a pair of values using a single noUISlider

I'm trying to achieve something unique with a noUIslider range by outputting two values. While I've managed to display the same value twice using examples from the noUIslider documentation, my goal is to have one of the outputs show a value that ...

Can we create an alias for the import path in TypeScript?

import A = require('../../distant/PathToA'); import B = require('./different/path/PathToB'); I am utilizing external modules (commonJS) and browserify, with WebStorm as my editor. If this were just regular javascript, there are severa ...

An error was encountered while attempting to redirect in an Angular 4 project, the URL was set up for HTTPS

I've been attempting to access an Angular 4 project deployed locally on my machine through a form on an HTML page: <!DOCTYPE html> <html> <body> <form action="https://test-pubg.sohum.com:4200" target="_blank" method="post"> ...

Verify the user's activity status in the MySQL database using Node.js by checking the timestamp of their last login

I have a query regarding user activity and deletion from the database. I need to determine when a user last logged in to see if their account is inactive. Unfortunately, I am unsure of how to tackle this task or check for the last login time. If anyone c ...

Guide to increasing a field value in Backendless.com

Below is an overview of the table structure I have: Table data ---------------------------------- - User - ---------------------------------- | objectId | name | password | ---------------------------------- | z12ttttt | ...

What is the best way to send a POST request with parameters to a PHP backend using AJAX?

This is an updated version of a previous question that was identified as a duplicate (How can I send an AJAX POST request to PHP with parameters?) I am currently sending an AJAX request to a PHP backend. Here are the JavaScript functions used to make and ...

Enhance your JavaScript code by using the powerful Node.js util.format() method

I have been attempting to enhance the functionality of the node.js util.format function by allowing it to be used as a prototype (for example: "Hello %s".format("World")). Unfortunately, my attempts have all failed. I've tried different formats like: ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Is it possible to dispatch actions from getters in Vuex?

Fiddle : here Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that t ...