Search code examples
angulartypescriptangular5viewportmeta-tags

conditional viewport meta tag in index.html


I have an angular module with two sub modules in it, one for user and the other for admin. of course they share the same index.html file.

in my user module I would like to have the <meta name="viewport" content="width=device-width, initial-scale=1"> in the <head></head> tags in index.html

While I want it to be removed in my admin module and just have the desktop view for phones as is.

I tired to do this in the admin first component constructor :

import { Meta } from '@angular/platform-browser';
this.meta.removeTag('name="viewport"'); 

the tag is being removed but that is after the app started rendering with the existence of this meta tag since it is in index.html so it does not give the desired result

any suggestions to have actually add this meta conditionally? the hard part is that it should be in the head of index.html.


Solution

  • It seems that you have to manually set the viewport to something else. Try removing the meta tag and setting it to something else, like in this example:

    https://www.quirksmode.org/blog/archives/2011/06/dynamically_cha.html

    If you view the following example from mobile, it will show the response view first (set in the index.html) and then after 5 seconds it will show the desktop version.

    import { Component, OnInit } from '@angular/core';
    import { Meta } from '@angular/platform-browser';
    import { timer } from 'rxjs';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
    })
    export class AppComponent implements OnInit {
      constructor(
        private readonly meta: Meta
      ) { }
    
      ngOnInit(): void {
        timer(5000).subscribe(() => {
          this.meta.removeTag('name="viewport"');
          this.meta.addTag({ name: 'viewport', content: 'width=1000' })
        })
      }
    
    }