Using ternary operator to calculate property value in Angular

Viewed 1007

I am a React developer getting started with one of my first Angular projects. I am trying to calculate the value to be assigned to a property in my markup based on a value passed from the parent component. I am using a ternary operator to decide the value to be assigned, but it is causing a compiler error. Please see my code below:

Parent component calling my custom component:

<gcp-three-dot-progress-bar [step]="2"></gcp-three-dot-progress-bar>

Component .ts file

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

@Component({
  selector: "gcp-three-dot-progress-bar",
  templateUrl: "./three-dot-progress-bar.html",
  styleUrls: ["./three-dot-progress-bar.scss"],
})
export class ThreeDotProgressBar implements OnInit {
  @Input("step") step: number;

  ngOnInit() {
  }
}

Component .HTML file

<mat-progress-bar mode="determinate" value="{{step => 2 ? 100 : 50 }}" class="vertical-progress-bar"></mat-progress-bar>
<p>{{step}}</p>

The error I am getting reads as follows:

Uncaught Error: Template parse errors: Parser Error: Bindings cannot contain assignments at column 7 in [{{step => 2 ? 100 : 50 }}] in...

As I am sure you can tell, I want to use the 'step' variable to determine the value of the 'value' property, but I suspect I am doing something fundamentally wrong. If I comment out the first line in my custom component, I can see that the correct value is coming through in 'step' in the 'p' on the second line, so I believe I am receiving the correct value.

I've tried doing a search for similar implementation, but I think I might not have the Angular terms straight yet since I can't seem to find anything similar (though I am convinced there must be some out there).

If anyone might be so kind as to point me in the right direction either with a reference or some advice on what to search, or by pointing out my mistake, I would be very grateful.

1 Answers

You can use template-syntax to bind value attribute like:

<mat-progress-bar 
  mode="determinate" 
  [value]="step >= 2 ? 100 : 50" 
  class="vertical-progress-bar">
</mat-progress-bar>

Also, I think this here:

step => 2 ? 100 : 50

is a typo. In case you want to check if step is greater than or equal to a value, then we need to use >= expression, instead of doing => which represent an arrow function expression in javascript.

Related