user441058
user441058

Reputation: 1278

Alternative to ng-container without the comments?

When using ng-container it gets rendered as an HTML comment:

<div>
    <ng-container>foo</ng-container>
<div>
will produce this kind of output :

<div>
    <!--template bindings={}-->foo
<div>

Is there an Angular alternative for ng-container that doesn't produce the comments in the HTML? I ask b/c my app creates legal documents dynamically from a database and each document will be a few dozen pages long and each page has many many components on it that are generated using ng-container with ng-switch. When I look at the HTML source I see 90% of the page are these rendered comments and it also takes up to ten seconds to generate a page dynamically. I haven't counted, but I expect that there are thousands of extraneous comment lines in the page. So I'm hoping to get rid of all the clutter in the HTML and hopefully that can speed up page generation as well. Although my page is generated dynamically, after it's generated the structure doesn't change. For example, I don't need Angular to be able to go back and switch our a text input for with a label. It's static.

Here is a small code snippet to give you an idea of how I'm handling things:

<ng-container *ngFor="let ctrl of formTemplate">
  <ng-container [ngSwitch]="ctrl.component">

   <ng-container *ngSwitchCase="'textinput'">
      <label *ngIf="!hasAttribute('nolabel', ctrl.attributes)" class="col-sm-2">{{ctrl.displayText}}</label>
      <ng-container *ngIf="!ctrl.readOnly">
        <div *ngIf="hasAttribute('full', ctrl.attributes)" class="col-sm-10">
          <input type="text" class="form-control" style="width:100%" [formControlName]="ctrl.key" />
        </div>
      </ng-container>
      <ng-container *ngIf="ctrl.readOnly">
          <ng-container *ngIf="hasAttribute('full', ctrl.attributes)">
              <label class="col-sm-10" style="font-weight: 100">{{protocol[ctrl.objectName][ctrl.fieldName]}}&nbsp;</label>
            </ng-container>
        </ng-container>
    </ng-container>

Upvotes: 1

Views: 2565

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105449

Is there an Angular alternative for ng-container that doesn't produce the comments in the HTML

Angular needs to have some DOM node in the template to be able to insert elements after it. In the case of ng-container it's comments. With the router it's router-outlet. Any DOM node can act as an anchor.

Here is the example using native DOM API that shows what Angular does:

const comment = document.createComment('ng-container - insert after me');
document.body.appendChild(comment);
const span = document.createElement('span');
span.textContent = 'I am inserted after comment';
document.body.insertBefore(span, comment.nextSibling);

Check this plunker.

If there's no DOM node (no comment in the case of ng-container), Angular doesn't have any DOM node to act as an anchor.

Upvotes: 2

Related Questions