0

I am using a dynamic component in my angular app. It's working fine but I want to change the html template it uses, For example in my dynamic component.ts I have:

@Component({
  selector: 'app-dynamic',
  template: '<p>Stackoverflow</p>' ,
  styleUrls: ['./dynamic.component.css']
})

So in the decorator instead of a html string can I use a variable which I get from some other service that holds required html string ? like:

@Component({
  selector: 'app-dynamic',
  template: variablehavinghtml,
  styleUrls: ['./dynamic.component.css']
})

I tried using templateUrl to link a html which has a div like:

<div [innerHTML]="variablehavinghtml"></div>

but as my variable can also have tags with angular property bindings it's not working so I have to give the html string inside my component decorator. So how can I do this?

Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32

1 Answers1

0

You could either enable angular routing, and the just redirect to all the app bodies you need, or you can define all the possible components in app.component and just display them if on a correct route:

import { ActivatedRoute } from '@angular/router'; in app.component.ts

constructor(..., private route: ActivatedRoute) { } to initialise the routing.

Let's create a variable r that will keep the first route parameter:

Place this.route.pathFromRoot[1].url.subscribe(val => { this.r = val.toString(); }); in ngOnInit()

In your html code, if you're at localhost:4200/forum as an example, and you want to have something only your forum will contain, you can do:

<div *ngIf="input == 'forum'">
    <!-- Content here will be only displayed on the forum route -->
    ...
</div>
  • the actual app is far more complex, I represented in a simple way and yes it has multiple routing modules, but my requirement is to display a html in the same path. I get lot of html strings so I can't possibly create routes for each of them. – Ramesh Reddy Sep 06 '19 at 11:14
  • Oh! I see! So you want to stay on the same route, but change the contents of the page? An example would be [Tabs](https://www.w3schools.com/bootstrap4/bootstrap_navs.asp) (Go down to _Toggleable / Dynamic Tabs_; you'll have to import jQuery for this one) But something like that would work. –  Sep 06 '19 at 11:23
  • It's not about changing contents, more about displaying them as I mentioned I have to display html that has tags with angular property bindings. Something like this [https://stackblitz.com/edit/dynamic-raw-template] but I don't want to create an NgModule in the component ts. – Ramesh Reddy Sep 06 '19 at 11:55