简体   繁体   中英

Angular 2: How to access dynamically created template variables

I have an app that loads in json from database and distributes the response to an accordion interface. My goal is to show the first response as expanded and all others as closed.

<div #areaLevel class="parent_div" *ngFor="let level_1 of [1,2,3]">
   <div class="chlid_div" [hidden]="areaLevel.expanded">

        <div class="button" [class.closed]="areaLevel.expanded" (click)="areaLevel.expanded = !areaLevel.expanded">
            <div class="plus">+</div>
            <div class="minus">-</div>
        </div>

        {{ level_1.content }}

   </div>
</div>

How should I go about editing "areaLevel.expanded" variable, so that, on load, it would be true for the first element and false for the others. Preferable solution is using only template, but other suggestions are also welcome.

I'm not sure I follow your question 100%

It's generally not considered good practice edit data from template. This is because its likely Angular will render the template first, and then run the template missing your changes. So it can lead to errors.

I think you want to maybe keep track of if its expanded on the object you are looping through

so in your component your ngInit might look like

levels = [];

constructor(private levelService: LevelService) { }

onInit() {

   levelService.subscribute(data=> {

      for (let i = 0; i < data.length; i++) {
          levels.push({
            content: data.content,
            expanded: false;
          })
      }

      levels[0].expanded = true;

   });
}

Then your template:

<div class="parent_div" *ngFor="let level_1 of levels">
   <div class="chlid_div" [hidden]="level.expanded">

        <div class="button" [class.closed]="level.expanded" (click)="level.expanded = !level.expanded">
            <div class="plus">+</div>
            <div class="minus">-</div>
        </div>

        {{ level.content }}

   </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM