Include links to external CSS and JS files within an Angular 2 component

To exclusively use "Bootstrap Select" in my.component.ts, I attempted the following approach:

@Component({
  templateUrl: 'my.component.html',
  styleUrls: [
        'my.component.css',
         //Bootstrap Select
        'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css'
  ]
})

However, I encountered the following error :

Can't resolve './https://cdnjs.cloudflare.com/...' in 'C:.....\app\components'

It appears that Angular 2 is looking for Bootstrap within my local directory. Is there a way to specify that it should search for an external URL instead?

In addition, I also need to include my JavaScript link:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

Answer №1

Referencing angular styles documentation.

Utilizing Style URLs from metadata

You have the ability to incorporate styles from external CSS files by including a styleUrls attribute in a component's @Component decorator:

 @Component({
      selector: 'hero-details',
      template: `
        <h2>{{hero.name}}</h2>
        <hero-team [hero]=hero></hero-team>
        <ng-content></ng-content>
      `,
      styleUrls: ['app/hero-details.component.css']
    })
    export class HeroDetailsComponent {
    /* . . . */
    }

The URL is regarded as relative to the application root, typically where the index.html web page that hosts the application is located. The style file URL does not rely on the component file. Hence, the example URL starts with src/app/. To specify a URL relative to the component file, refer to Appendix 2.

It is also possible to embed tags within the component's HTML template.

Similar to styleUrls, the link tag's href URL is maintained relative to the application root, not the component file.

@Component({
      selector: 'hero-team',
      template: `
        <link rel="stylesheet" href="app/hero-team.component.css">
        <h3>Team</h3>
        <ul>
          <li *ngFor="let member of hero.team">
            {{member}}
          </li>
        </ul>`
    })

Incorporating CSS @imports

You can also import CSS files into other CSS files using the standard CSS @import rule. For further information, refer to @import on the MDN site.

In this scenario, the URL is based on the CSS file you are importing into.

@import 'hero-details-box.css';

If necessary, adjusting encapsulation may be required for your purpose. Here's an explanation on it. Check out Load external css style into Angular 2 Component for insights. It offers a solution for integrating an external CDN, but I aim to provide comprehensive details and reasons why it is essential. Rest assured, this method addresses your specific case.

Additionally, there are suggestions above that assist in adding script tags. My recommendation is to directly add it to your component template, ensuring that what is unique to your component is included directly in the html.

Answer №2

In order to properly link your CSS file, make sure to use a relative path.

Start by using "./" followed by the path to your CSS file, for example: "/styles/my-stylesheet.css".

As for the second CSS file being referenced, you can include it in your index.html file like this:

<link rel="stylesheet" href="https://example.com/css/another-stylesheet.css">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for broadcasting a router event

Currently, I am working with 2 modules - one being the sidenav module where I can select menus and the other is the content module which contains a router-outlet. I am looking for the best way to display components in the content module based on menu selec ...

CSS technique for arranging text in order?

My website has a unique layout where certain text appears differently on desktop and mobile devices. Specifically, I have a simple text that looks like this on desktop: Kolor : Niebieski Rozmiar : S/M However, I want it to appear like this on mobile: Ko ...

Modify the dropdown menu title dynamically based on the selection made in Angular

My Angular web-application has a dropdown menu that looks like this: <div class="btn-group" dropdown> <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN <span class="caret"></span>&l ...

What is the mechanism by which nodes handle multiple requests simultaneously?

Lately, I've delved into the world of NodeJs, trying to grasp how it handles multiple concurrent requests. It's fascinating that NodeJs operates on a single-threaded event loop architecture, where only one statement executes at a time on the main ...

What is a way to incorporate two ngClass directives within a single div element?

Is it possible to include two ng-class directives within a single div element? If so, how should we go about writing them together? Thank you for your help. <div [ngClass]={'white-background': policyNumber.length <= 0} [ngClass]="getS ...

Looking to prevent horizontal scrolling on smartphones in an HTML webview - how can I do this?

Currently, I am dealing with a webview and encountering some peculiar behavior. The overflow-x property is set to hidden, which works perfectly on browsers. However, when accessed on a mobile device, the overflow seems to be ignored completely. Here is t ...

Making AJAX requests with Laravel using the XMLHttpRequest object is a

When using Laravel to upload a file and create a progress bar with ajax requests, the form action routes to the controller in this way: <form action="{{ URL::route('upload-file-form-post') }}" method="POST" enctype="multipart/form-data"> ...

Angular: Enhancing table functionality by implementing a search bar and customized filters for content refinement

Currently, I am working on a project involving a datatable with various filtering options: https://i.sstatic.net/uFFWP.gif The HTML code snippet is as follows: <div class="row topbuffer-20"> <div class="col"> <h3>Thief: The Dark ...

React Application Issue 'Error: React is not defined'

I've been working on developing an app using react, but for some reason, it's not functioning properly and I'm struggling to pinpoint the issue. The code compiles without errors using babelify, however, it throws an exception during executio ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

What could be causing the mysql-event to not function properly in a Node.js environment?

const MySQLEvents = require('mysql-events'); const databaseInfo = { host: 'localhost', user: 'root', password: '' //blank password }; const mysqlEventWatcher = MySQLEvents(databaseInfo); console.log(mys ...

Issue with npm version: 'find_dp0' is not a valid command

Hello, I have a small node application and encountered an issue while running a test. The error message displayed is as follows: 'find_dp0' is not recognized as an internal or external command, operable program or batch file. It seems to be re ...

What are the steps to utilizing the $document service in AngularJS?

I am a complete beginner when it comes to AngularJS and JavaScript in general, and I find myself a bit confused about the usage of $document. From what I understand, $document provides access to some JQuery functions. So, if I want to remove an element tha ...

Using Bootstrap datepicker to show dates in Month YYYY format and then sending the data to server as MMYYYY for processing

Utilizing the bootstrap datepicker to select a date has been smooth sailing so far. However, due to certain server limitations, we now need to submit the data in the format "022021" rather than "Feb 2021". How can we achieve this post-formatting and submis ...

Implementing a Bootstrap 4 modal in Webpack 2

Utilizing only the bootstrap modal functionality, I manually included the required libs (modal.js & util.js) in the vendor section of webpack.config.js If I directly add the vendor.js file, everything works fine. However, since it is bundled, I prefer ...

Error: module 'next/react' not found

Recently delving into next.js, I encountered an error after creating a project with npx create-next-app. Oddly enough, the app still runs despite this issue. { "resource": "/E:/codes/news-website/news-website/pages/index.js", ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

What is the process for assigning one file input to another file input?

Quite an unusual question, I admit. The crux of the matter is my utilization of a fantastic tool known as cropit. With this tool, we have the ability to upload an image, preview it, and then manipulate it according to our preferences. HTML: <div align ...

I find myself struggling to maintain the context of `this` within the Backbone View

I am currently working on enhancing my typeahead feature with debounce functionality. So far, I have achieved some success with the following code. The code successfully debounces the request. However, I encountered an issue where when I define a functio ...

What could be causing setTimeout to trigger ahead of schedule?

I am struggling with a piece of node.js code like this: var start = Date.now(); setTimeout(function() { console.log(Date.now() - start); for (var i = 0; i < 100000; i++) { } }, 1000); setTimeout(function() { console.log(Date.now() - s ...