georgej
georgej

Reputation: 3311

Angular 2 - styles dont work in AOT build

I am using this function to add style to my component if the parameter widget=true is present in the url:

addStyleSheet() {
  var headID = document.getElementsByTagName('head')[0];
  var link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.id = 'widget_styles';
  headID.appendChild(link);

  link.href = './app/open-account/open-account-widget-styles.component.css';
}

It works perfectly when built Just In Time (JIT) but does not work when built in Ahead Of Time (AOT). Why is that and how can I fix it?

Upvotes: 1

Views: 142

Answers (1)

Owain van Brakel
Owain van Brakel

Reputation: 3349

Let's use a simple example to explain this. Imagine this is your route:

{ path: '/widget', component: WidgetComponent }

You can navigate to that route with parameters using the following code:

this.router.navigate(
  ['/widget'], { queryParams: { widget: 'true' } }
);

This will result in the following URL /widget;widget=true Note: Angular uses an semicolons for separating the params instead of a question mark.

Documentation can be found here

In your component you can get the params like this:

this.route
  .queryParams
  .subscribe(params => {
    this.widget = params['widget'] === 'true';
  });

At this point you have a variable with the param in your component you can now use conditional styling.

<div [ngClass]="{class_name: widget}">Lorum ipsum</div>

This way you never touch the DOM directly and angular will handle everything.

Upvotes: 1

Related Questions