[英]How to use *ngIf in index.html angular 8
如何在 Angular2+ 中的index.html
中使用 *ngIf 条件。 我想使用*ngIf
根据条件加载标签,因为我在本地存储中有一个值。 这是我的代码,但它不起作用。
<head *ngIf="localStorage.getItem('theme_token') === 'site-layout'"></head
当我使用脚本标签时,它会在 javascript 中获取主题令牌的值。
<script>
var _val = localStorage.getItem('theme_token'); /// This part is working returning me the value.
</script>
注意:我不想隐藏。 我必须使用
*ngIf
条件渲染它。
*ngIf 不会为您解决问题。 *ngIf 将在 angular 内工作。 试试这个例子可能会有所帮助。 它与 angular 8 一起使用。在您的应用程序组件中。
constructor() {
if (localStorage.getItem('theme_token') === 'site-layout') {
const temp = document.createElement('link');
temp.innerHTML = '<link id="default-css" href="assets/somestyle.css" rel="stylesheet" media="all">'
;
const head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
}
}
您可以根据自己的情况进行加载。
据我所知,Angular 应用程序(其中大多数)具有<app-root></app-root>
应用程序引导的入口点,这意味着从这一点开始 angular 将进入图片(内存)然后你让您的路线、其他组件、angular 按照您构建应用程序的方式进行填充。
现在你想在 index.html 中使用*ngIf
index.html
所以点就是你将绑定这个index.html
的地方,即使用哪个组件来提供你的*ngIf
变量,即使你只添加*ngIf='true'
它也会被渲染因为它没有任何影响或副作用
你能做什么(可能)
<scrip></script>
访问 DOM 来处理普通 JS,按照你想要的方式进行更改app.component.ts
的ngOnInit
中访问 DOM 并执行此操作。 浏览器不知道它与*ngIf
有什么关系,它是 angular 知道*ngIf
的含义和这个特定点 angular 尚未加载
您不能在外部使用 *ngIf。 我们有多种方法可以在纯 javascript 中做同样的事情。 Go 与 vanila js 无副作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.