1

I want to use a @Component inside a table, but I think I can't use Angular
<tags> inside the elements <tr> of a table. I can't use a @Directive because I want to include html. What should I do?

I have the following in my-page.html:

<tr my-tag SOME_THINGS></tr>

Then, in my-component.ts I have

@Component({
  selector: '[my-tag]',
  templateUrl: './my-tag.html',
  styleUrls: ['./my-tag.scss']
})

and in my-component.html I have:

<td>blah blah blah</td>

@Component is called inside a tr as a directive but it's not, because I want to include some html in it.

This raises the following tslint error:

The selector of the component "my-tag" should be used as element (https://angular.io/styleguide#style-05-03) (component-selector)

If I do the following:

@Component({
  selector: 'app-my-tag',
  templateUrl: './my-tag.html',
  styleUrls: ['./my-tag.scss']
})

together with

<tr><app-my-tag></app-my-tag></tr>

I don't get lint errors, but it looks really weird to me, and I lose the style of the rows.

Which would be a possible solution?

Thank you!

xavier
  • 1,860
  • 4
  • 18
  • 46
  • 1
    Directives can manipulate the `DOM`. Use a directive. – The Head Rush Mar 27 '19 at 17:21
  • Directives can manipulate the DOM, but can they add html? I think not. Sorry, but I don't fully understand your remark... :-( – xavier Mar 27 '19 at 18:18
  • 1
    Manipulating the DOM is actually more powerful than the ability to "add html" via a component - yoou can conditionally add, remove or change existing elements to the DOM parsed from an html document or snippet. – The Head Rush Mar 27 '19 at 19:22
  • That sounds really interesting! Do you know any reference of how to parse the html document? Thank you! – xavier Mar 28 '19 at 11:44

2 Answers2

1

just use selector: 'tr[my-tag]'. With such selectors you define your specific trs

Vega
  • 27,856
  • 27
  • 95
  • 103
Andrei
  • 10,117
  • 13
  • 21
  • 1
    If I use this notation, I get the lint error `The selector of the component "my-component" should be named kebab-case and include dash (https://angular.io/styleguide#style-05-02)`. So, it seems it doesn't solve my problem...? – xavier Mar 28 '19 at 11:33
1

Yes, you can append html elements from the directive. Here's how:

import { AfterViewInit, Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appTestDir]'
})
export class TestDirective implements AfterViewInit {
  constructor(private elRef: ElementRef, private renderer: Renderer2){}

  ngAfterViewInit(): void {
    const div = this.renderer.createElement('div');
    const divText = this.renderer.createText('I am text inside div');
    this.renderer.appendChild(div, divText);
    this.renderer.appendChild(this.elRef.nativeElement, div);
  }
}

In Your HTML

<td appTestDir>Blah Blah Blah</td>

This produces: Blah Blah Blah I am text inside div

Don't forget to add your Directive to the declarations array in NgModule.

Anjil Dhamala
  • 1,544
  • 3
  • 18
  • 37