0

Using Angular, I am calling a function inside a .html file, which returns a string containing a table element. I want this string to convert to html code.

I have tried [innerHtml]:

<p [innerHtml]="kalenderen(forsteUkedag('2016-08-01' | date:'E'), 8, 2016)"></p>

This works, printing the table, but the problem is that inside the table I have id/classes, unique for each cell, and I am not able to access them inside the .html file using this method. Styling the table from a CSS file is also not working. And I want to avoid inline CSS.

Any suggestions how to solve this so I can access the id/classes/objects? Thanks in advance!

MariusJ
  • 195
  • 2
  • 16

1 Answers1

1

Maybe you don't need to insert html directly, what about this:

<p>
    <table id="yourId" class="yourClass">
        <tr>
            <td *ngFor="let cell of cells" 
                [attr.id]="cell.id">{{cell.text}}</td>
        </tr>
    </table>
</p>

Put all your html to the template, and component class only deals with data.

And in your component:

// Cell is like this:
// {id: string; text: string}
cells: Array<Cell[]>;
ngOnInit() {
    this.cells = this.getCells();
}
getCells() {
    let cells = .........;
    return cells;
}
peng37
  • 4,480
  • 1
  • 11
  • 13
  • I have tried, it did not work. I use a function to create the table cells, outputted as a string. So putting it inside {{ }} would only print the string, not running it as html code. – MariusJ Oct 10 '16 at 20:42
  • What i mean is, don't create html string(the table cells) in a function, just put all the html structure in the template, like:
    {{cellInfo}}
    , and only create the cellInfo property with functions
    – peng37 Oct 11 '16 at 09:49
  • I can't, because I have functions to determine how many cells the table should have, not only putting a content in them. – MariusJ Oct 11 '16 at 11:04
  • What about *ngFor? It will render the cells you give to it dynamically, no matter how many. – peng37 Oct 11 '16 at 12:02
  • You mean like

    {{calendar}}

    ? It doesn't show the table.
    – MariusJ Oct 11 '16 at 12:19
  • The problem is that I want all single cells to have a unique id. As far as I know, this will not work for that purpose. A solution might be that my function inside component exports it's return value to the html file? Is that possible? – MariusJ Oct 11 '16 at 14:41