user12484971
user12484971

Reputation:

How to use *ngIf in index.html angular 8

How can I use *ngIf condition in index.html in Angular2+. I want to load tags based on condition using *ngIf for that I have a value in local storage. Here is my code but it is not working.

<head *ngIf="localStorage.getItem('theme_token') === 'site-layout'"></head

When I used script tag it get the value of theme token in 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.

Upvotes: 4

Views: 5987

Answers (3)

Kamran Khan
Kamran Khan

Reputation: 1109

*ngIf wouldn't do the trick for you. *ngIf will work inside angular. Try this example may this helps. It worked with angular 8. In your app component.

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

       }
}

You can load according to your condition.

Upvotes: 2

Monis
Monis

Reputation: 175

As far as I am aware Angular application (most of them) has entry point of <app-root></app-root> where the application is bootstrapped, means from this point angular will come into the picture(memory) and then you have your routes, other components, angular stuff the way you have structured the application.

Now you want to use *ngIf in index.html, so point is where you will bind this index.html i.e. with which component to supply your *ngIf variable and even if you will just add *ngIf='true' it will be rendered as it is without any effect or side-effect

What you can do (possibly)

  1. Try to do with plain JS via <scrip></script> access DOM, change it the way you want
  2. If you want to do with Angular only, then in app.component.ts in ngOnInit access the DOM and do it.

enter image description here

enter image description here

Browser doesn't know what it has to with *ngIf, It is the angular that knows the meaning of *ngIf and this particular point angular not loaded yet

Upvotes: 1

Sumit Sinha
Sumit Sinha

Reputation: 329

You can't use *ngIf outside . We have multiple ways to do the same in pure javascript. Go with vanila js for no side-effetcs.

Upvotes: 1

Related Questions