Search code examples
polymer

Polymer 3 - Using stylesFromTemplate


I'm a novice using Polymer 3 and need to get styles from an element. Can anyone show me a real world example of how to use stylesFromTemplate? I'm struggling.

stylesFromTemplate(template: !HTMLTemplateElement, baseURI: string)

For example, using Polymer Starter Kit (https://github.com/Polymer/polymer-starter-kit), a function in my-app.js that gets the styles from my-view1.js - thanks!


Solution

  • Here you go update the _pageChanged method of the my-app component with the following:

    //Dont´forget to import the function
    import { stylesFromTemplate } from '@polymer/polymer/lib/utils/style-gather.js';
    
    _pageChanged(page) {
        import(`./my-${ page }.js`).then((viewModule) => {
            let view = new viewModule.default();
            console.log(stylesFromTemplate(view._template, window.location));
        });
    }
    

    Don´t forget to update my-view1.js, my-view2.js, my-view3.js, my-view404.js by making these js module export the webcomponents classes as default

    export default class MyView1 extends PolymerElement ...