Home > database >  How can I toggle the style of a paragraph using [ngStyle] and ternary on Angular?
How can I toggle the style of a paragraph using [ngStyle] and ternary on Angular?

Time:04-28

I am new to Angular. I try to toggle the paragraph using a method. I declared two variables that contain my object for the style of my paragraph. My problem is I got an error

Error: src/app/directives-sample/directives-sample.component.html:6:7 - error TS2322: Type 'string' is not assignable to type '{ [klass: string]: any; }'.
  Type 'string' is not assignable to type '{ [klass: string]: any; }'.

6 <div [ngStyle]="!isSpecial ? 'currentStyles' : ''">
        ~~~~~~~

  src/app/directives-sample/directives-sample.component.ts:5:16
    5   templateUrl: './directives-sample.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component DirectivesSampleComponent.

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

× Failed to compile.

Here's my code:

//html

<div [ngStyle]="isSpecial ? 'currentStyles' : 'specialStyles'">
    This div is initially italic, normal weight, and extra large (24px).
</div>

//ts

export class DirectivesSampleComponent implements OnInit {
  isSpecial: boolean = false;
  currentStyles = { 'font-style':'italic','font-weight': 'bold', 'font-size': '24px', 'color': 'red'};
  specialStyles = { 'font-style':'italic','font-weight': 'italic', 'font-size': '16px', 'color': 'blue'};
  constructor() { }

  ngOnInit(): void {
  }

  toggleSpecial() {
    this.isSpecial = !this.isSpecial;
  }

How can I solve this problem?

CodePudding user response:

The way you are providing value to [ngStyle] is incorrect.

Check: angular doc for NgStyle

Correct way could be to provide specialStyles & currentStyles as is and not as string:

[ngStyle]="!isSpecial ? currentStyles : specialStyles"

CodePudding user response:

I suggest you make use of ngClass instead of ngStyle and you can begin by creating your 2 style classes like below:

.currentStyles {
  font-weight: bold;
  font-style: italic;
  font-size: 24px;
  color: red
}

.specialStyles {
  font-weight: italic;
  font-style: italic;
  font-size: 16px;
  color: blue
}

Then in your paragraph, you can have the following:

<div [ngClass]="isSpecial ? 'specialStyles' : 'currentStyles'">
    This div is initially italic, normal weight, and extra large (24px).
</div>
  • Related