Search code examples
angularwidgetstylesheet

Angular 2 - if query string present, load another stylesheet


I have an Angular 2 app and want to turn one of my components into an iframe widget when the query string widget=true is present. When this string is present I want to load an additional stylesheet into the component to change the widget view a little bit. Is this possible? How would I do this?

Just to clarify:

I have a component that I use as a regular page but want to be able to have it as an iframe widget too. When the query string widget=true is present I will know that the page is in an iframe. In this case I want to load an additional stylesheet to the component


Solution

  • Well there are several ways.

    First, obvious and dirty, is including styles as <style> tag with *ngIf checking for this parameter in the URL.

    Second, what I find better, is setting the style into styleUrls component meta property:

    let styleUrls = [];
    
    if (window.location.href.contains('widget=true')) {
      styleUrls.push('/path/to/style');
    }
    
    @Component({
      selector: 'hero-app',
      template: `
        <h1>Tour of Heroes</h1>
        <hero-app-main [hero]=hero></hero-app-main>`,
      stylesUrls: 
    })
    export class HeroAppComponent {
    /* . . . */
    }