user8055794
user8055794

Reputation:

How can i dynamically call my css file on index.html - angular2

My requirement is i need to call a css url from a variable. Actually i dont want to hard code it. As per the logged in user , the name of the css will be downloaded in local storage and from there i want to load it on index.html, how can i make this possible ?

My index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Wbuilder</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="./assets/files/css/style.css">
  // instead of this i need to call this from a variable

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

Upvotes: 1

Views: 3454

Answers (3)

Anishnirmal
Anishnirmal

Reputation: 558

This may help someone. Instead adding a file, if there are minimal dynamic css you can include it. A dynamic generated CSS at the controller can be bind to the HTML View using ng-bind-html attribute with in the style tag.

Have a look at http://www.codeexpertz.com/blog/angularjs/adding-dynamic-generated-csscascading-style-sheet-angularjs-view-example for Demo and Sample Code

HTML

    <style ng-bind-html="myStyle"></style>
    <span>Enter the background colour value:</span>
    <span><input type = "text" ng-keyup="updateChanges()" ng-model = "bgcolour"></span>
    <br/>
    <div class="codeexpertz">
    </div>

SCRIPT

    app.controller("myCtrl", function($scope) {
    $scope.bgcolour = '11acfd';
    $scope.updateChanges = function(){
        $scope.myStyle= '.codeexpertz { background-color: #' + $scope.bgcolour + '; height: 100px; width: 100px; border: 1px #000 solid}';
    }
    $scope.updateChanges();

Upvotes: -1

Harleen Kaur Arora
Harleen Kaur Arora

Reputation: 2087

Open your main style.css( This file be under app folder ) file and write top on the code this line:-

style.css

@import "/assets/files/css/style.css";

Upvotes: 0

Dean Chalk
Dean Chalk

Reputation: 20471

Why not create an Angular component that dynamically generates an in-line <script>tag that includes a dynamically generated @import statement that loads the css. This component will be added to your root component template.

So the template for the dynamic css component may look like this:

<style>
   @import "{{dynamicCssFileLocation}}.css";
</style>

With this dynamic css component's selector in your mainn index.html file it should load this dynamic file from the variable dynamicCssFileLocation

Upvotes: 2

Related Questions