如何在 index.html angular 8 中使用 *ngIf

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>

Note: I don't want to hide. I have to render it using *ngIf condition.

据我所知,Angular 应用程序(其中大部分)的入口点为 <app-root></app-root>,应用程序在此处被引导,意味着从这一点开始 angular 将进入图片(内存)然后你有你的路线,其他组件,angular按照你构建应用程序的方式填充。

现在你想在 index.html 中使用 *ngIf,所以关键是你将绑定这个 index.html 的地方,即用哪个组件提供你的 *ngIf 变量,甚至如果您只添加 *ngIf='true' 它将按原样呈现,没有任何 effectside-effect

你能做什么(可能)

  1. 尝试通过 <scrip></script> 访问 DOM 来处理纯 JS,按照您想要的方式进行更改
  2. 如果您只想使用 Angular,那么在 app.component.tsngOnInit 中访问 DOM 并执行它。

浏览器不知道它与 *ngIf 有什么关系,是 angular 知道 *ngIf 的含义并且这个特定点 angular 未加载还

您不能在外部使用 *ngIf。我们有多种方法可以在纯 javascript 中做同样的事情。使用 vanila js 没有副作用。

*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);
        }

       }
}

您可以根据自己的情况加载。