6

I have a component like this below:

@Component({
  selector: 'app-car-item',
  templateUrl: './car-item.component.html',
  styleUrls: ['./car-item.component.css'],
})
export class CarItemComponent {
  public style: string

  addStyle() {
    this.style = 'font-size: 20px'
  }

How can I implement addStyle() method to change size of font in car-item.component.css?

2
  • I believe you are best using the ngStyle directive to pass an object from your html element to your typescript (conditionally if you wish) Commented Aug 22, 2018 at 21:24
  • Or you can use ViewChild directive to access the element of interest in your DOM and apply a style that way Commented Aug 23, 2018 at 8:19

2 Answers 2

5

This is not how you do it in Angular! This is how you would do it:

In your CarItemComponent add a vairable for the font-size for example:

fontSize: number;

In your addStyle() set this number to the font size you want to use and in your template add this to the element which's font-size you want to change:

[style.font-size.px]="{{ fontSize }}"
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I'm newbie in Angular. Where exactly do I have to add this line: [style.font-size.px]="{{ fontSize }}" ?
In your template on the element whichs font-size you want to change: <div [style.font-size.px]="{{ fontSize }}">content</div>
0

This could be useful (Angular 6):

  1. Change styles in order to look like disabled
  2. Eliminate the href

https://stackblitz.com/edit/angular-wzgr4h

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.