EN VI

Angular 17 attribute selector for component not working?

2024-03-11 01:00:07
How to Angular 17 attribute selector for component not working

I am learning angular 17 with standalone components and I cannot get the attribute selector to work with my component.

As explained in the documentation, I should be able to use an attribute for my component https://angular.dev/guide/components/selectors#types-of-selectors

When I try it, I get the following error

Can't bind to 'app-list-item' since it isn't a known property of 'tr'.

I tried making a type and class selector and these work as expected. When using the attribute selector. I get an error.

Here are my angular components. A stackblitz of the problem can be found here: https://stackblitz.com/edit/angular-17-starter-project-4t9qcr?file=src%2Flist.component.ts

list-item-component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-list-item, .app-list-item, [app-list-item]',
  standalone: true,
  imports: [],
  template: `         
          <td>{{ item.A }}</td>
          <td>{{ item.B }}</td> 
  `,
  styles: ``,
})
export class ListItemComponent {
  @Input() item!: { A: string; B: string };
}

list.component.ts

import { Component } from '@angular/core';
import { ListItemComponent } from './list-item.component';

@Component({
  selector: 'app-list',
  standalone: true,
  template: `
    <div> 
      <h3>Type selector</h3>
        <table> 
          <tr>
            <th>A</th>
            <th>B</th>
          </tr>
          @for (item of data; track $index){
            <tr>
            <app-list-item [item]="item"/>  
          </tr>
          }
        </table> 

        <h3>class selector</h3>
        <table> 
          <tr>
            <th>A</th>
            <th>B</th>
          </tr>
          @for (item of data; track $index){
            <tr class="app-list-item" [item]="item"></tr>
            
          }
        </table> 

        <h3>Attribute selector</h3>
        <table> 
          <tr>
            <th>A</th>
            <th>B</th>
          </tr>
          @for (item of data; track $index){
            <tr [app-list-item] [item]="item"></tr>
          }
        </table> 
    </div>
  `,
  styles: ``,

  imports: [ListItemComponent],
})
export class ListComponent {
  data = [
    { A: 'a1', B: 'b1' },
    { A: 'a2', B: 'b2' },
  ];
}

when you remove<tr [app-list-item] [item]="item"></tr> it works as expected, but I would prefere a solution with an attribute.

Solution:

it should be

<tr app-list-item [item]="item"></tr>
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login