Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an ngModel inside an ng-template which is repeated using *ngFor

I have a ng-template which is repeated using an *ngFor. I am passing additional data to the template from ngFor using ngTemplateOutletContext. With this data that I am passing to the template I am creating a dropdown list. I have this stackblitg example showing a code extract of what I have done.

Data

data = {
 row1_ID: {
  'article 1': 'Lorem Ipsum is simply dummy text ',
  'article 2': 'Lorem Ipsum has been the industry standard dummy text ',
},
 row2_ID: {
  'article 1': 'aldlsadalskjd;asjsa;kdj dalskdjaslkjd',
  'article 2': 'Lorem ipsum dolor sit ame',
 },
};

HTML

<div *ngFor="let row of data | keyvalue">
   <ng-container 
       [ngTemplateOutlet]="OpRef2"
       [ngTemplateOutletContext]="{ data: row.value, id: row.key }">
   </ng-container>
</div>

<ng-template #OpRef2 let-data="data" let-id="id">
  <div class="row">
     <h2>Row ID: {{ id }}</h2>
     <select>  <!--Using ng model here doesnt work-->
        <option *ngFor="let article of data | keyvalue" [value]="article.key">
        {{ article.key }}
        </option>
     </select>
  <div>
  <!--I would like the contect of this do change based on what's selected in the dropdpwn but varaibles created in the context of ng-template are readonly hence nh-model doesnt work-->
  <div>{{ data['article 1'] }}</div>
</div>

Now based on the values selected in the dropdown I want the content below it to change. But since its a template, any varianle I create are readonly and can't be used in the ngModel for the select. Also I cant use an external variable list as the rows in the data property are fetched from an API and I cant be sure how many rows it would contain.

Is there any way of achiving this?

like image 709
BiJ Avatar asked Oct 21 '25 05:10

BiJ


1 Answers

If its only to be able to change de between articles you could do it without binding the ngModel to a property and accesing the ngModel value through a template variable.

It would be something like this.

<div class="row">
  ...
  <select ngModel #articleSelected="ngModel">
    ...
  </select>

  <div>
    <div>{{ data[articleSelected.value] }}</div>
  </div>
</div>

Cheers

like image 64
akotech Avatar answered Oct 23 '25 18:10

akotech