首页 > 解决方案 > 如何动态更改模板html

问题描述

我在我的角度应用程序中使用动态组件。它工作正常,但我想更改它使用的 html 模板,例如在我的动态 component.ts 中,我有:

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

所以在装饰器中而不是 html 字符串中,我可以使用从其他一些包含所需 html 字符串的服务中获得的变量吗?喜欢:

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

我尝试使用 templateUrl 链接具有 div 的 html,例如:

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

但是由于我的变量也可以具有带有角度属性绑定的标签,因此它不起作用,因此我必须在组件装饰器中提供 html 字符串。那么我该怎么做呢?

标签: angular

解决方案


您可以启用角度路由,并直接重定向到您需要的所有应用程序主体,或者您可以定义所有可能的组件app.component并在正确的路由上显示它们:

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

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

让我们创建一个变量 r 来保留第一个路由参数:

放入this.route.pathFromRoot[1].url.subscribe(val => { this.r = val.toString(); });_ngOnInit()

在您的 html 代码中,如果您localhost:4200/forum以示例为例,并且想要拥有只有您的论坛将包含的内容,您可以执行以下操作:

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

推荐阅读