2

How can I prevent the <app-componentName> tag from being added to Angular HTML output? Let me explain what I mean with an example:

I have a chat-box and a message component like this:

<div class="chatbox">
    <app-message-component 
         *ngFor="let message of messages" [myInput]="message">
    </app-message-component>
</div>

after I serve or build the output in HTML is:

<div class="chatbox">
    <app-message-component>
        <div> message 1 </div>
    </app-message-component>
    <app-message-component>
        <div> message 2 </div>
    </app-message-component>
    ...
</div>

But I want it to be this: (Without <app-message-component>s):

<div class="chatbox">
    <div> message 1 </div>
    <div> message 2 </div>
    ...
</div>

Note that this was "an example" to explain the problem and this particular example has a variety of solutions (for example, I can write ngFor inside the component, but this is not my question).

My question is how does <app-componentName> not appear in the HTML output generally?

Saeed sdns
  • 804
  • 7
  • 17
  • 2
    Does this answer your question? [Angular2 : render a component without its wrapping tag](https://stackoverflow.com/questions/38716105/angular2-render-a-component-without-its-wrapping-tag) – Michał Tkaczyk Oct 30 '20 at 07:57

2 Answers2

3

from @staeke

class NoRootTagComponent implements OnInit {
    @ViewChild(TemplateRef) template;

    constructor(private vcRef:ViewContainerRef) {}

    ngOnInit() {
        this.vcRef.createEmbeddedView(this.template);
    }
}

@Component({
  template: `<ng-template>
<tr>...</tr>
<tr>...</tr>
</ng-template>`
})
class SomeRowsComponent extends NoRootTagComponent {
   constructor(vcRef:ViewContainerRef) {
        super(vcRef);
    }
}

Or

@Component({
  selector: 'div[app-message-component]',
  ...
})

then

<div app-message-component><div>
ttquang1063750
  • 803
  • 6
  • 15
-1

Try to create an inner div (inside of the app-message-component) and put the *ngFor inside of there, so it creates several divs instead of whole AppComponents