How to Pass Value from Ts File to SCSS File in Same Component in Angular 2+

How to pass value from typescript code to css in Angular 6

Use class

<div [class]="'col-'+ widthValue"></div>

OR

Use style.width

<div [style.width]="(widthValue/12)*100 + '%'"></div>

DEMO

Access component variable inside SCSS file Angular 2

Oukei, the solution I found to work around that is actually simple and it does let you use component variables inside styles.

You basically use [ngStyle] directive to change the property of an element.

example.component.ts

@Component({
selector: 'example-selector',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css']
})
export class ExampleComponent {
@Input() size: number;
}

example.component.html

<div [ngStyle]="{ 'width': 'calc(100% - ' + size + 'px)' }"></div>

or you can use calc to divide with

<div [ngStyle]="{ 'width': 'calc(100% / ' + size + ')' }"></div>

or use any other given property like that.

And you can also have classes defined for that element and have a specific (or multiple) properties defined with ngStyle.

Thanks.

Angular get scss style in TS

You can set a variable in your scss file like this (at the top of the file)

:root {
--myWidth: 25vh;
}

then use it in ur scss file

element {
width: myWidth;
}

And u can access it in your TS file

//get your value
var styleProperty= element.style.getPropertyValue("--myWidth");

// set your value
element.style.setProperty("--myWidth", "50vh");

How to transfer data between two components in a same .ts file

Somehow I managed to transfer data through parameters and services to modal component, But having these types of components on a same page is not an appropriate way to implement Angular. So i break apart AppModalComponent as a saperate component and import it into the module of AppComponent

app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-component',
template: 'app.component.html',
styleUrls: ['./app-component.css']
})
export class AppComponent{
instruction:any;
constructor() { }
}

app-modal.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-modal-component',
template: 'app-modal.component.html'
})
export class AppModalComponent{
constructor() { }
}

app.module.ts

import { AppModalComponent } from '../path-to-import-app-modal.component';

@NgModule({
declarations: [
...,
...,
AppModalComponent
],
imports: [],
exports:[],
providers: []
})

export class AppModule { }

This was the easiest and required way to get data through components, it only gets easy from here.



Related Topics



Leave a reply



Submit