首页 > 解决方案 > 如何隐藏 ngFor 的 div 并根据之前的 ngFor 显示

问题描述

我想获取我单击的特定年份的月线,以便能够将其链接到更多数据集。


<div class="list-float-right">
    <ul >                  
      <li *ngFor="let years of yearData">
        <a href=#{{years.year}}>{{years.year}}</a> 
          </li>
    </ul>
  </div>

  <hr>

  <div class="list-float-right">
    <ul>                  
      <div *ngFor="let years of yearData">
        <li *ngFor="let months of years.monthData">

            {{months.month}}


        </li>
              <br>
     </div>
    </ul>
  </div>

  <div *ngFor="let years of yearData">
    <div id={{years.year}}>
      {{years.year}}
      <br>
          The color of animals <br>is by no means <br>a matter of chance;
           <br>it depends on many considerations, 
           <br>but in the majority of cases tends to protect the animal 
           from danger by rendering it less conspicuous. 
       <hr>
      </div>

yearData = [{
    year:2019,
    monthData: [
      { month : "jan"},
      { month : "july"}
    ]
  },{
    year:2018,
    monthData: [
      { month : "march"},
      { month : "april"}
    ]
  },{
    year:2017,
    monthData: [
      { month : "march"},
      { month : "dec"}
    ]
  },{
    year:2016,
    monthData: [
      { month : "march"},
      { month : "feb"}
    ]
  },{
    year:2015,
    monthData: [
      { month : "jan"},
      { month : "may"}
    ]
  }
];

每年和每个月的数据都相互关联。因此,如果我单击 2019 年,然后选择在给定年份可用的年份。

输出格式

year bar
给定 year 可用的月份 bar 。

如果没有选择年份,它会自动指向最近的年份月份。就像在给定的 json 中一样,它应该给出 2019 年的月份。

预期产出

2019 2018 2017 2016 2015 // 如果我点击 2018 它将显示在下一行

3 月 4 月 // & 如果我没有点击任何年份,它将给出 2019 年。

标签: angularngforangular8

解决方案


试试下面的代码

HTML

<div class="list-float-right">
    <ul>
        <li *ngFor="let years of yearData">
            <a href=#{{years.year}} (click)="selectedYear = years.year">{{years.year}}</a>
        </li>
    </ul>
</div>
<hr>
<div class="list-float-right">
    <ul>
        <div *ngFor="let years of yearData">
            <ng-container *ngIf="years.year === selectedYear">
                <li *ngFor="let months of years.monthData">
                    {{months.month}}
                </li>
            </ng-container>
        </div>
    </ul>
</div>

<div *ngFor=" let years of yearData">
    <ng-container *ngIf="years.year === selectedYear">
        <div id={{years.year}}>
            {{years.year}}
            <br>
          The color of animals <br>is by no means <br>a matter of chance;
           <br>it depends on many considerations, 
           <br>but in the majority of cases tends to protect the animal 
           from danger by rendering it less conspicuous. 
       <hr>
      </div>
        </ng-container> 
  </div>

打字稿

selectedYear: any;

ngOnInit() {
  selectedYear = yearData.map(value=> value.year).sort((a, b) => a+b)[0];
}

推荐阅读