angular2-polyfill icon indicating copy to clipboard operation
angular2-polyfill copied to clipboard

Retrieve styleUrls content

Open SamVerschueren opened this issue 10 years ago • 5 comments

At the moment, we support styles and styleUrls for components. They work like this.

@Component({
    selector: 'home',
    template: '<h1>Foo Bar</h1>'
    styles: [`
        h1 {
            color: red;
        }
    `],
    styleUrls: [`app/component/style.css`]
})
class HomeComponent {

}

Which will result in the following tags being added and removed at runtime. Just like Angular2 does.

<style type="text/css">@charset "UTF-8";h1 { color: red; }</style>
<link rel="stylesheet" href="app/component/style.css">

But the difference at the moment is that Angular 2 actually reads the content of style.css which will result in the following output.

<style type="text/css">@charset "UTF-8"; h1 { color: red; }</style>
<style type="text/css">@charset "UTF-8"; h1 { color: green; }</style>

It is nicely explained in this Thoughtram article.

How does this work? When is the content from the css file loaded? What's the benefit over working with the link tag?

SamVerschueren avatar Feb 25 '16 18:02 SamVerschueren

@jvandemo Any idea how this works? Maybe @pascalprecht wants to join the discussion and elaborate :)?

SamVerschueren avatar Feb 25 '16 18:02 SamVerschueren

I think Angular 2 parses the stylesheets (instead of linking to the original stylesheets) to be able to namespace them.

See this plunk to see how Angular namespaces the component styles.

Would have to dig into the Angular source code to see how they accomplish this.

Maybe @PascalPrecht knows more indeed as he has been reading a lot of the source code already ;-)

jvandemo avatar Feb 26 '16 09:02 jvandemo

It seems like they indeed namespace the components with _nghost and a random letter combination.

screen shot 2016-02-26 at 10 10 08

screen shot 2016-02-26 at 10 10 18

The question is, when do they do that and how does it impact performance? Parsing the CSS and adding the namespaces seems like an expensive operation.

SamVerschueren avatar Feb 26 '16 09:02 SamVerschueren

Here is the Angular 2 magic: https://github.com/angular/angular/blob/master/modules/angular2/src/compiler/style_compiler.ts

SamVerschueren avatar Mar 10 '16 09:03 SamVerschueren

:+1:

jvandemo avatar Mar 10 '16 09:03 jvandemo