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.
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>
Share Improve this question edited Jun 13, 2020 at 7:48 Monis 1752 silver badges12 bronze badges asked Jun 13, 2020 at 7:40 user12484971user12484971 1Note: I don't want to hide. I have to render it using
*ngIf
condition.
- You can take your index.html inside to app.ponent.html then you can use ngIf there – Cagri Tacyildiz Commented Jun 13, 2020 at 7:57
3 Answers
Reset to default 2*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 ponent.
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.
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.
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 e into the picture(memory) and then you have your routes, other ponents, 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 ponent 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)
- Try to do with plain JS via
<scrip></script>
access DOM, change it the way you want - If you want to do with Angular only, then in
app.ponent.ts
inngOnInit
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