Adding fewer components to your current Angular 5 project

I have a JS Fiddle showcasing a CSS chart. How can I integrate LESS into my current Angular 5 project to make use of this chart? Also, where should I place the JavaScript and references to the LESS file from this example within my Angular component? The link to the JSFiddle is provided below.

JavaScript:

$('head style[type="text/css"]').attr('type', 'text/less');
less.refreshStyles();

http://jsfiddle.net/andydesrosiers/fwaLt99a/

Answer №1

When working with Angular components, you typically have a html file, a typescript file, and a style file (usually css):

my-comp.component.html
my-comp.component.ts
my-comp.component.less     <-- defaults to css

If you want Angular to use .less files instead of .css and compile them during the build process, follow these steps:

  • Open the .angular-cli.json file in your project and set the property defaults.styleExt to "less".

  • For each existing component that currently uses css but needs to be switched to less, rename the style file and ensure that the typescript file references the correct stylesheet:

    @Component({
      selector: 'app-my-comp',
      templateUrl: './my-comp.component.html',
      styleUrls:  ['./my-comp.component.less']
    })
    

Answer №2

While my solution may not be the most optimal, it has been effective for me. Since I do not have access to a node server, I keep the SCSS file within the project. I compile it online to generate the CSS, which I then reintegrate into the project. This means that both files are still present, but the SCSS remains untouched. Whenever I need to make changes to the CSS, I update the SCSS as well and recompile it to overwrite the previous CSS file. Although this method may not be the most secure, it is a practical workaround when setting up a new server is not feasible for addressing dynamic styling issues. For larger projects, it might be worth considering implementing a node server or similar solution to ensure the safety of your LESS files.

Answer №3

Andy, I have discovered that Angular actually supports many css preprocessors, including less. With this newfound knowledge, I can offer you a potential solution to your problem. You can create a component as shown below.

-voltage-meter.component.ts

import { Component, OnInit, ViewEncapsulation, Input } from '@angular/core';

@Component({
  selector: 'app-voltage-meter',
  templateUrl: './voltage-meter.component.html',
  styleUrls: ['./voltage-meter.component.less'],
  encapsulation: ViewEncapsulation.None
})
export class VoltageMeterComponent implements OnInit {
  @Input() voltage: number;
  constructor() { }

  ngOnInit() {
    console.log(this.voltage);
  }

}

-voltage-meter.component.less (simply paste your less code in this file)

-voltage-meter.component.html

<div class="radial-progress" attr.data-progress='{{voltage}}'>
    <div class="circle">
        <div class="mask full">
            <div class="fill"></div>
        </div>
        <div class="mask half">
            <div class="fill"></div>
            <div class="fill fix"></div>
        </div>
        <div class="shadow"></div>
    </div>
    <div class="inset">
        <div class="voltage"><div class="voltage-in-use">Voltage in use</div></div>
    </div>
</div>

You can then use the component like so:

<app-voltage-meter [voltage]='12'></app-voltage-meter>

I was able to make this work by using the Angular CLI to generate the project and assigning it the less preprocessor.

ng new less-test --style=less

This will allow you to incorporate the less code from your jsfiddle example.

I apologize once again for my earlier mistake and thank you to seven-phases-max for pointing out the error.

Edit: For an existing project, refer to this article and replace scss with the preprocessor you are utilizing.

Angular-cli from css to scss

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

How about incorporating a unique twist while utilizing a for loop to attach click listeners?

I've been exploring, but I'm unable to find a solution to this particular issue. I am working with a linked list that needs to be accessed when specific items on my webpage are clicked. To do this, I created a get(id) method that iterates throug ...

File extension being lost when dropped in AJAX request

I am currently working on a script that uses AJAX to delete an image. PHP foreach ( $in_folder as $img => $v ) { echo ' <span class="imageHolder"> <a onclick="DeleteImage('.$img.'); return false;" href="j ...

Encountering a Tailwindcss error while attempting to compile the CSS file

Struggling to grasp Tailwind CSS as I try to compile the CSS but keep encountering errors. Despite following numerous tutorials, this persistent error continues to hinder my progress. This is the specific error message that keeps popping up: $ npm run bui ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

In internet explorer with AJAX, the UI is refreshed by Javascript only when an alert() function is triggered

Having an issue in Internet Explorer, works perfectly in Firefox. There is a javascript function that updates the UI (screen content) before an AJAX call. However, it does not update the UI unless an alert box prompt is used. Without the alert box, the UI ...

Unable to retrieve data from SpringBoot controller using $http.get request

I have developed an application that will execute queries on my store's database based on user input on the webpage. The backend method is functioning correctly and returns the response, but I am having trouble displaying the data in a dynamic table o ...

Angular: No routes found that match the URL segment

I encountered an issue with my routes module where I am receiving the error message Cannot match any routes. URL Segment: 'edit-fighter' when attempting to navigate using the <a> link. The only route that seems to work is the champions-list ...

Error in AngularJS v1.2.5 when using textarea with placeholder attribute in IE11

Having trouble with an Angular JS v1.2.5 form that is not functioning in IE11, despite working perfectly in Firefox, Chrome, and Safari. The issue seems to be related to using interpolation inside the placeholder attribute of a textarea. <body ng-con ...

Creating a sliding menu using React and Headless UI (with Tailwind CSS)

Currently, I'm in the process of developing a slide-over navigation bar or slide menu that features panels opening on top of each other (I'm still searching for the most accurate way to describe it). The main concept revolves around having a sli ...

How can I retrieve the array data that was sent as a Promise?

I have a database backend connected to mongoDB using mongoose. There is a controller that sends user data in a specific format: const db = require("../../auth/models"); const User = db.user const addProduct = (req, res) => { User.findOne({ ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Having difficulty transferring information from the component to the service

I am having trouble passing a parameter to a function that is defined in a service. No matter what I try, the parameter always ends up being undefined. login.component.ts import { Component, OnInit } from '@angular/core'; import { Authenticati ...

Having trouble resolving this issue: Receiving a Javascript error stating that a comma was expected

I am encountering an issue with my array.map() function and I'm struggling to identify the problem const Websiteviewer = ({ web, content, styles, design }) => { const test = ['1' , '2'] return ( {test.map(item => { ...

How can I align an image and text alongside another image using HTML and CSS?

Having some trouble positioning an Image and Text next to another Image. Check out an example here: I attempted using floats, but it doesn't seem to be working. Here is the code I have: .left {float: left;} .right{float: right;} <div class="left ...

Angular - Filtering only ag-Grid information

I am currently working on implementing print functionality for ag-Grid in an angular project. I have a page that includes both content and ag-Grid data. When I attempt to use the print functionality, both the content and grid data are being printed. Howeve ...

Difficulties in Adjusting the Size of Three Image Columns within a Website's Body

While working on my website layout, I encountered a problem with inserting three image columns in the body section. The images turned out to be too large and extended beyond the footer. Moreover, the third image was larger than expected, dominating the web ...

Adjusting ToggleButton hues in react-bootstrap

I am working with a group of ToggleButtons in my app and I want to customize their background colors. Currently, all the buttons have a gradient defined by <.untoggled-button> class, with an added blue overlay for unselected buttons. However, I am fa ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...

Change the background color of a MUI ToggleButton based on a dynamic selection

const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({ "&.Mui-selected, &.Mui-selected:hover": { backgroundColor: selectedColor, } })); const FilterTeam = (props) => { const [view, setView] = ...