使用NgFor代替HTML

时间:2018-11-05 19:51:19

标签: html angular ngfor

我对棱角还比较陌生,我知道必须有一种比我正在做的更好的方法。我想使用ngfor遍历并吐出此信息,而不是手动输入所有信息。有什么建议吗?

这是我的代码:

<section class="eighth-section our-work">
    <h2 class="uppercase">Our work</h2>
    <a target="blank" href="">
        <img class="lazy our-work__img"
             src="./assets/images/our-work/kma-logo.png"
             alt="KMA Logo"></a>
    <a target="blank" href="https://fwchiro.com/forms/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/DF_FWChiroLogo.png"
             alt="Functional Wellness Chiropractic logo"></a>
    <a target="blank" href="https://www.608motorsports.com/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/DF_608logo.png"
             alt="608 Motorsports Logo"></a>
    <a target="blank" href="https://dektex.com/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/DF_dektexlogo.png"
             alt="DekTex Logo"></a>
    <a target="blank" href="https://kswconstruction.com/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/DF_KSWLogo.png"
             alt="KSW Construction Logo"></a>
    <a target="blank" href="https://bzcustomfinishing.com/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/DF_BZlogo.png"
             alt="BZ Custom Finishing Logo"></a>
    <a target="blank" href="https://familyfirstverona.com/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/DF_famfirstlogo.png"
             alt="Family First Logo"></a>
    <a target="blank" href="https://hamiltonconcretepro.com/">
        <img class="lazy our-work__img"
             src="./assets/images/ourwork/Hamilton_Logo.png"
             alt="Hamilton Concrete Logo"></a>
</section>

我想用于循环的项目是以下标签: src href alt

谢谢!

2 个答案:

答案 0 :(得分:3)

在您的组件中:

public links = [
  {src: 'your_src_1', href: 'your_href_1', alt: 'your alt text 1'},
  {src: 'your_src_2', href: 'your_href_2', alt: 'your alt text 2'},
  {src: 'your_src_3', href: 'your_href_3', alt: 'your alt text 3'},
  {src: 'your_src_4', href: 'your_href_4', alt: 'your alt text 4'},
];

在您的模板中:

<a *ngFor="let link of links" target="blank" [href]="link.href"><img class="lazy our-work__img" [src]="link.src" [alt]="link.alt"></a>

应该可以解决问题

关键是您需要在某个地方包含所有参数对象的数据数组。那么您可以使用ngFor遍历它们并使用数据集结果。

答案 1 :(得分:-1)

您可以在JS中有一个绑定到HTML的对象。这是一个样本。您应该在其中添加所有7个项目。

$scope.foo = [
    {'href' : '',
     'src': '',
     'alt': ''}
]

在您的HTML中,您将使用ng-repeat来实现循环:

<section class="eighth-section our-work">
  <h2 class="uppercase">Our Work</h2>
    <div ng-repeat="item in foo">
      <a target="blank" href="item.href"><img class="lazy our-work__img" src="item.src" alt="item.alt"></a>
    </div>
  </section>