The art of combining Angular 6 with CSS styling for dynamic

Can we dynamically set a value in an scss file from the ts component like demonstrated below?

public display: "none" | "block";
ngOnInit(): void {
    this.display = "none";
}


::ng-deep #clear {
    display: {{display}} !important;
}

The ID clear is within a component that was sourced from a library installed via npm.

Answer №1

It's not feasible to do it that way; however, you could incorporate CSS in the following manner:

<div id="reset" [style.display]="display ? 'block': 'none'">
   ....
</div>

Answer №2

If you can imagine wanting to change the theme of your template from light mode to dark after clicking on a button, you will need to ensure that all components in your template also switch themes accordingly. One approach is to create an Angular service and update the property isDarkMode upon button click. You can then subscribe to this property in each component as shown below:

in theme.service.ts

private _isDarkMode = new Subject<boolean>();
isDarkMode = this._isDarkMode.asObservable();

setDarkTheme(isDarkTheme: boolean): void {
  this._darkTheme.next(isDarkTheme);
}

in test.component.ts

ngOnInit(): void {
    this.isDarkMode = this.themeService.isDarkMode
}

in test.component.html

<div [ngClass]="{'test-dark-mode': isDarkMode }"></div>

To streamline this process, consider using mixins. By creating a mixin for styling the test component template (e.g., @mixin creat-test-theme($theme)) and subscribing to isDarkMode only in app.component.ts, you can avoid repeating subscriptions in every component.

in app.component.ts

ngOnInit(): void {
    this.isDarkMode = this.themeService.isDarkMode
}

in app.component.html

<div [ngClass]="{'dark-mode': isDarkMode }"></div>

In your app.component.scss file, define the .dark-mode class and include the mixin to apply the current theme to each component when the dark-mode class is added to the DOM.

.dark-mode {
  @include creat-test-theme($dark-theme)
}

This way, with the addition of the dark-mode class, your components will automatically adjust to the selected theme.

Answer №3

After reviewing your feedback, it appears that you may be utilizing a component in need of programmatically adding styles to it within Angular but lacking direct access to the component itself.

If the suggested solutions do not meet your requirements, resorting to plain javascript is always an option, although it may not be the most elegant solution.

constructor(private document : Document) {

}

ngOnInit() {
  this.document.getElementById('clear').style.display = 'none';
}

However, exercise caution with this method as it can be somewhat heavy-handed and requires careful consideration.

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

Angular definitely typed does not convert into JavaScript

After installing TypeScript on my VS2013, I obtained the Angular 1.5 Definitely Typed from the NuGet package manager. Although angular.d.ts and its components do not generate angular.js file, when I create another TypeScript file like file1.ts, the file1. ...

Facing issues during the unit testing of an angular component method?

I'm facing an issue with a unit test that is failing. Below is the code for reference: Here is my typescript file: allData: any; constructor(@Inject(MAT_DIALOG_DATA) private data, private dialogRef: MatDialogRef<MyComponent>, priva ...

Visual Studio Code is unable to identify the TypeScript module located within the `node_modules` directory

After cloning the tslint repository, running npm install and grunt as instructed in the README, I opened the folder in Visual Studio Code (0.9.1). Upon inspecting a .ts file such as src/rules/typedefRule.ts, TypeScript errors appeared regarding the require ...

Guide to configuring Nodemailer with Angular 4

I've been searching everywhere for a tutorial that can walk me through the steps of setting up nodemailer in Angular 4. I'm feeling lost about where to place the ts code snippet from nodemailer's website: 'use strict'; const nodem ...

Tips for defining the type of any children property in Typescript

Currently, I am delving into Typescript in conjunction with React where I have a Team Page and a slider component. The slider component is functioning smoothly; however, my goal is to specify the type of children for it. The TeamPage import react, { Fragm ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

Retrieve data from an HTML form within an Angular 2 ag-grid component

I'm facing a challenge with incorporating form values from a modal into an ag-grid array in my HTML file. I'm unsure of the process to achieve this. Below is an excerpt from my file.html: <template #addTrainContent let-c="close" let-d="dismi ...

What is the best way to detect a change in a property using rxjs?

My Angular6 application has a simple input tag: <input type="text" name="searchBox" [(ngModel)]="searchTerm" class="form-control" /> I want to create an observable of the searchTerm property in order to apply operators like debounce, etc. How can I ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

Guide to Setting Up "Remember Me" Login for Users in Angular

I am having trouble setting the 'Remember Me' option on my Login page. I tried using localstorage session but it seems like something is missing in the service file that's causing it not to respond properly. I attempted to follow a guide on ...

Setting up Microsoft Clarity for your Angular app on localhost is a simple process

Currently, I am attempting to set up Microsoft Clarity on my Angular app to run on localhost. After creating a new project on the Microsoft Clarity portal and specifying the URL as localhost (I also tried using localhost:4200</code), I copied the scrip ...

React-router-dom TypeScript error when defining the type of the prop parameter in the loader

I'm having trouble with the params prop in the loader prop within the routes. I've defined the params in TypeScript, but I'm getting errors that I don't understand. Any help would be appreciated, thanks in advance. I tried to use the Cu ...

Top Tips for Updating the CSS of a Nebular ngx-admin Component

If I want to modify the behavior or CSS style of a Nebular/NGX-admin component, what is the best way to go about it? I have tried adjusting the module directly in node_modules/@nebular, but I'm not sure if this is considered a good practice. Is ther ...

Using TypeScript to automatically deduce the output type of a function by analyzing the recursive input type

I am currently working on developing an ORM for a graph database using TypeScript. Specifically, I am focusing on enhancing the "find" method to retrieve a list of a specific entity. The goal is to allow the function to accept a structure detailing the joi ...

Utilizing trackingjs as an external library in Ionic2

I have been attempting to incorporate the trackingjs library (https://www.npmjs.com/package/tracking) into my ionic2 project. Following the guidelines in the documentation (https://ionicframework.com/docs/v2/resources/third-party-libs/), I was able to suc ...

What are the steps to execute jest in an AWS Lambda environment?

I'm looking to execute my end-to-end test post-deployment for the ability to revert in case of any issues. I've followed the guidelines outlined in this particular blog post. Below is my lambda function: export async function testLambda(event: A ...

How can you utilize both defineProps with TypeScript and set default values in Vue 3 setup? (Typescript)

Is there a way to use TypeScript types and default values in the "defineProps" function? I'm having difficulty getting it to work. Code snippet: const props = defineProps<{ type?: string color?: 'color-primary' | 'color-danger&a ...

What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used Object.assign({}, xyz) and other times they used Object.assign([], abc); Could there be a distinction between the two methods? ...

Declare that a method alters a value with state

Here's a more streamlined version of my code. Check out my custom hook below: export const useStep = () => { const [step, setStep] = useState<Steps>("sending"); const changeStep = (newStep: Steps) => setStep(newStep); return { ste ...

Sending JSON data from Angular to WCF

Attempting to utilize the post method in Angular to send JSON data to a WCF service. The data is being sent in JSON format from Angular, however, the WCF service is receiving it as a null object. Is it possible to use the get method to send JSON data? Th ...