alok alok - 1 year ago 138
TypeScript Question

Angular2 - fetch json value to replace value into html template

New to angular2, having problems infetching the value from the Footer[] array and display it.


import { Component } from '@angular/core';

export class Footer {
id: number;
value: string;

const FOOTER : Footer[] = [
{id: 1, value: 'value_one'},
{id: 2, value: 'value_two'}

selector: 'footer',
template: `<html-outlet [html]="footerValue"></html-outlet>`,
export class FooterComponent{
foot = FOOTER;

footerValue = `<div class="menu" *ngFor="let f of foot" >
<div class="footer"><b>{{f.value}} @2016</b></div>

The sinnept:

template:`<html-outlet [html]="footerValue"></html-outlet>`,

takes the template from 'footerValue' and sends to another function for compiling and loading the html dynamically.

All works well if its passed directly as:

template: `<div class="menu" *ngFor="let f of foot" >
<div class="footer"><b>{{f.value}} @2016</b></div>

Can someone guide me how to append the values from the array to the string variable 'footerValue', to follow my original functionality to generate the html dinamically.

Original html template is :

`<div class="menu" *ngFor="let f of foot" >
<div class="footer"><b>Example @2016</b></div>

where the 'Example' should get replaced with value from the array.

Answer Source

I guess the problem is that your html-outlet tries to "compile" your html-snippet but don't know what foot is..

So prepare your html-snippet like this:

constructor() {
   this.footerValue = this.prepareFooterHtml();

prepareFooterHtml(): string {
   let footer = '<div class="menu">';
   this.foot.forEach(f => {
      footer += `<div class="footer"><b>${f.value} @2016</b></div>`;
   footer += '</div>';
   return footer;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download