Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - ngfor without wrapping in a container

Tags:

angular

I wish the have a ul element and then in my json I have html containing list (li) elements from various social media sites.. when I put ngfor on the list items is creates multiple ul's for each of the outputted json records.. is it possible just to output each of the li's as plain html and not wrap them in an element

small sample of my json

{
    "courses": [{
        "tile_id": 0,
        "tile_content": "<li class=\"grid-item horiz-double blog-tile\" data-item-id=\"0\">yrdy<\/li>"
    }],
}

small sample of my angular service - this works perfectly and outputs the json but maybe im missing some kind of formatting setting

public getCourses() {

    this._http.get(this.apiUrl).map(response => response.json()).subscribe(data => {
        // console.log( data.courses );
        this._dataStore.courses = data.courses;

        // console.log(this._coursesObserverXX);

        this._coursesObserverXX.next(this._dataStore.courses);

    }, error => console.log('Could not load courses.'));

}

and my html

<ul class="list-group" *ngFor="#course of courses | async">
      {{ course.tile_content }}
</ul>

the goal is to not have the ngfor output a wrapper and also to display the output as plain html rather than plaintext as it appears to come out

like image 251
Kravitz Avatar asked May 03 '16 13:05

Kravitz


3 Answers

In some cases, <ng-container> may be useful. Like (not for this specific question):

<ng-container *ngFor="let item of items; let i = index">
  ...
</ng-container>

In the DOM, its content is rendered as usual, but the tag itself is rendered as an HTML comment.

From the documentation:

Group sibling elements with <ng-container>

[...]

<ng-container> to the rescue

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

like image 82
Arjan Avatar answered Oct 22 '22 10:10

Arjan


You can use outerHTML

<ul class="list-group" >
  <li *ngFor="let course of courses | async" [outerHtml]="course.tile_content"></li>
</ul>

Plunker example

like image 36
Günter Zöchbauer Avatar answered Oct 22 '22 11:10

Günter Zöchbauer


Not sure to understand what you want / try to do but you can do something like this:

<ul class="list-group">
  <li *ngFor="#course of courses | async">
    {{ course.tile_content }}
  </li>
</ul>

Note that the expanded syntax could also be used:

<template ngFor [ngForOf]="courses | async" #course>
  {{ course.tile_content }}
</template>

(the template tag won't be added into the HTML)

Edit

This works:

<ul *ngFor="#elt of elements | async" [innerHTML]="elt.title">
</ul>

See this plunkr: https://plnkr.co/edit/VJWV9Kfh15O4KO8NLNP3?p=preview

like image 5
Thierry Templier Avatar answered Oct 22 '22 10:10

Thierry Templier