0

I am new to working with angular and I was reading through the documentation but I could not find the proper way to declare some kind of variable that can be reused in nested html elements.

As a work around I did something that works but I consider a bit dirty. I would like to know how a proper solution for this would look like.

Basically, what I have is the identifier 'someProperty' that I want to use in many places in the nested HTML elements. I may want to use it as the formControlName but also as an argument to function calls. Right now I abuse the *ngFor for this purpose to define variable 'x'.

<div class="container-row" *ngFor="let x of ['someProperty']">
  <span *ngIf="isReadOnly(x)" class="readonly-indicator"></span>
  <span *ngIf="!isReadOnly(x)" class="writable-indicator"></span>
  <mat-form-field>
    <input matInput type="number" formControlName="{{x}}"
           [readonly]="isReadOnly(x)"
           (change)="onChange($event, x)"
           placeholder="This is some Property!">
    <mat-error *ngIf="!someFormGroup.controls[x].valid">ERROR!</mat-error>
  </mat-form-field>
</div>
Nic.Star
  • 150
  • 1
  • 7
  • An alternative would be to abuse `*ngIf`. You can find other methods in [this post](https://stackoverflow.com/q/38582293/1009922). – ConnorsFan Mar 27 '20 at 14:05

2 Answers2

0

You can add a readonly variable in your component as use that property as a constant.

readonly MY_PROPERTY = 'someProperty'

And use it in your template like this

<div class="container-row" *ngFor="let x of [MY_PROPERTY]">

I hope this helps.

UPDATE:

<div class="container-row" *ngFor="let x of ([MY_PROPERTY] as templateVariable)">
{{ formGroup.controls[templateVariable].value  }} 
</div>
tedian_dev
  • 54
  • 4
  • Not really what I want. I want to specify the value of the variable in the HTML, not the component.ts file. I just don't want to have to copy the same string over and over. – Nic.Star Mar 27 '20 at 14:09
  • use either static variables, or @inputs to children or an event system which ask parent to emit variable value, this requires child to subscribe to the parent event. – JWP Mar 27 '20 at 14:17
0

i think what you need is FormArray that has form controls and you can get its value as array here see this post it will help you

here is one another one

If that's what you need, please approve this as an answer

Mohamed Enab
  • 129
  • 1
  • 11