alok alok - 1 day ago 4
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.

footer.component.ts:



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'}
];

@Component({
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>
</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>
</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>
</div>`


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

Answer

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;
}
Comments