简体   繁体   English

如何动态更改模板html

[英]how to change the template html dynamically

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: 它工作正常,但我想更改它使用的html模板,例如在我的动态component.ts中,我有:

@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 ? 因此,在装饰器中,我可以使用从其他拥有所需html字符串的其他服务获取的变量代替html字符串吗? like: 喜欢:

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

I tried using templateUrl to link a html which has a div like: 我尝试使用templateUrl链接具有div的html,例如:

<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. 但是由于我的变量还可以包含带有角度属性绑定的标签,因此它不起作用,因此我必须在组件装饰器中提供html字符串。 So how can I do this? 那我该怎么做呢?

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: 您可以启用角度路由,然后直接重定向到所需的所有应用程序主体,或者可以在app.component定义所有可能的组件,并在正确的路线上显示它们:

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

constructor(..., private route: ActivatedRoute) { } to initialise the routing. constructor(..., private route: ActivatedRoute) { }初始化路由。

Let's create a variable r that will keep the first route parameter: 让我们创建一个变量r,该变量将保留第一个route参数:

Place this.route.pathFromRoot[1].url.subscribe(val => { this.r = val.toString(); }); 放置this.route.pathFromRoot[1].url.subscribe(val => { this.r = val.toString(); }); in ngOnInit() 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: 在您的html代码中,如果您以localhost:4200/forum为例,并且希望仅在论坛中包含某些内容,则可以执行以下操作:

<div *ngIf="input == 'forum'">
    <!-- Content here will be only displayed on the forum route -->
    ...
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM