Search code examples
htmlangularinputdata-bindingdefault-value

How to use multiple variables in the [value] attribute of an input in Angular


I have a problem, I would like to do this:

<mat-form-field>
  <mat-label>Period:</mat-label>
  <input matInput [value]="period.month / period.year" disabled>
</mat-form-field>

But that does not work.

enter image description here


On the other hand, this works:

<mat-form-field>
  <mat-label>Period:</mat-label>
  <input matInput [value]="period.year" disabled>
</mat-form-field>

Would anyone have a solution to display multiple variables in the value of an input?

EDIT: [ngValue] does not work, I want to display a string of variables.


Solution

  • Since [value] needs a string, you could set its value to

    [value]="period.month + '/' + period.year"
    

    which resolves to a string. In your code, period.month is divided by period.year and resolves to NaN if at least one of them cannot be changed to a number.