Reputation:
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
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
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)
<scrip></script>
access DOM, change it the way you wantapp.component.ts
in ngOnInit
access the DOM and do it.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
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