Reputation: 83
what I want to do exactly is to render text coming from the backend as a part of the angular template with full features like interpolations and directives (ngfor, if, switch).
Here is a brief example
template.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styleUrls: ['./template.component.scss']
})
export class TemplateComponent implements OnInit {
names: string[];
template: string;
constructor(
private myService: MyService
) { }
ngOnInit() {
this.myService.getTemplate('page-name').subscribe(data => {
// say data = <span *ngFor="let name of names">hello {{name}}</span>
this.template = data;
});
this.myService.getNames().subscribe(data => {
// say data = ['name 1', 'name 2', 'name 3']
this.names = data;
});
}
}
template.component.html
<div [innerHTML]="sample"></div>
Current output
hello {{name}}
Desired output
hello name 1
hello name 2
hello name 3
here is the closest thing i found to what i need https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e
Upvotes: 3
Views: 324
Reputation: 1517
Say after your server response comes (in your case http) you call handleResponse() function.
handleResponse(response) {
this.name = response.name
// ...
}
then in you HTML file
<span>hello <span>{{name}}</span></span>
This is the normal angular practice. Also it's very easy to implement.
Upvotes: 0
Reputation: 1517
can't you do it like below. When data updates you can regenerate sample.
Say after your server response comes (in your case http) you call handleResponse() function.
handleResponse(response) {
this.sample = `<span>hello <span>` + this.name + '</span></span>`;
// ...
}
Your HTML file will remain the same
In a similar way you can use if, else ect rather than inIf...
In this way you can construct the html that should be displayed.
Upvotes: 1
Reputation: 8959
It should be like this:
name = `world!`;
sample = '<span>hello '+this.name+'</span>';
and in the html:
<div [innerHTML]="sample"></div>
Upvotes: 0