如何在 Angular 中创建动态视图

How to create dynamic view in Angular

我想使用从 json 文件中获取的数据动态创建多条水平线,如下图所示。 我试试看

Component.html

<div style="text-align: center">
  <div class="flex-items">
    <div *ngFor="let item of timelineObject">
      <h3 class="row text-center">{{ item.data }}</h3>
      <hr id="timeline" />
      <img style="" [src]="item.icon" />
    </div>
  </div>
</div>

Component.css

.flex-items {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
#timeline {
  display: inline-block;
  margin: auto;
  width: 10vh;
  border: 10px solid blue;
}

此处的 html 与您提供的不同,但我需要一些演示数据来复制预期的行为。这里的关键是 flex-box 属性 order。我用 属性 :nth-child 在每个偶数 div timeline-wrapper 上更改 h3img 的顺序。另请注意,为了始终在中间显示 hrh3img 必须具有相同的高度。

<div class="flex-items">
  <div class="timeline-wrapper">
    <h3 class="row text-center">2017</h3>
    <hr>
    <img src="https://picsum.photos/200" />
  </div>
  <div class="timeline-wrapper">
    <h3 class="row text-center">2018</h3>
    <hr>
    <img src="https://picsum.photos/200" />
  </div>
  <div class="timeline-wrapper">
    <h3 class="row text-center">2019</h3>
    <hr>
    <img src="https://picsum.photos/200" />
  </div>
  <div class="timeline-wrapper">
    <h3 class="row text-center">2020</h3>
    <hr>
    <img src="https://picsum.photos/200" />
  </div>
</div>

CSS

.flex-items {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.timeline-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

hr {
  background-color: blue;
  height: 5px;
  width: 100%;
}

h3,
img {
  height: 200px;
  margin: 0;
}

.timeline-wrapper:nth-child(2n) h3 {
  order: 2;
}

.timeline-wrapper:nth-child(2n) img {
  order: 0;
}

.timeline-wrapper:nth-child(2n) hr {
  order: 1;
}

这是一个fiddle:https://jsfiddle.net/w6nvfb4d/32/