angular - 如何动态更改模板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 字符串。那么我该怎么做呢?
解决方案
您可以启用角度路由,并直接重定向到您需要的所有应用程序主体,或者您可以定义所有可能的组件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>
推荐阅读
- visual-studio - CMake 中的 Visual Studio 项目引用
- java - 输出的动态 Web 服务器 servlet 问题
- amazon-web-services - AWS VPC Lambda 网络问题
- python - python堆积面积图
- flutter - mapEventToState 不使用 BLOC 模式触发,Flutter
- avaloniaui - Avalonia UI,背景模糊了我在 Render 中绘制的内容
- r - 如何将“更改”变量汇总为总变量?
- excel - 我想就如何自定义格式在excel中的特定数字寻求帮助
- sql-server - 将结果集限制为第一行中第一列的值?
- sequelize.js - 与 sequelize.where 重复的列名