【问题标题】:How to use for loop in "li tag href"如何在“li tag href”中使用for循环
【发布时间】:2019-07-11 02:51:41
【问题描述】:

如何创建一个包含 2 个对象“标题”和“链接”的数组,然后使用 for 循环?对于每个 (li a href) ?? 我正在使用角度

<div class="text-footer">
    <ul>
        <li>
            <a href="#abc">facebook</a>
        </li>
        <li>
            <a href="#abc">twitter</a>
        </li>
        <li>
            <a href="#abc">instagram</a>
        </li>
    </ul>
</div>

【问题讨论】:

  • 我不想适应(每个 li 标签的#abc 链接),只想把它放在数组中,然后对每个 li 使用 for 循环
  • 问题不清楚。请更具体并告诉我们您拥有什么以及您希望您的代码做什么
  • 我有 3 个 li 标签,每个 li 都有一个 href,我在每个 href 中放置了一个静态链接,我想将静态链接放到一个数组,该数组具有名称 title 和 link 然后使用 for 循环,但是我不知道如何
  • 我真的向开始学习 Angular [1] 的人推荐这个 Freecodecamp 课程:freecodecamp.org/news/…

标签: javascript html angular typescript


【解决方案1】:

这是一个例子

working Examlple

组件.html

<ul>
    <li *ngFor = "let title of fetchData">
       <a href="title.title">{{title.title}} -- {{title.description}} -- {{title.tagline}} {{title.date}}</a></li>

 </ul>

组件.ts

mydata = [
            {"title":"http://tombatossals.github.io/angular-leaflet-directive/#!/","description":"dd","tagline":"tt","date":"derd"},
            {"title":"http://tombatossals.github.io/angular-leaflet-directive/#!/","description":"fdfds","tagline":"tt","date":"rerrdd"},
            {"title":"http://tombatossals.github.io/angular-leaflet-directive/#!/","description":"dsfsdf","tagline":"tt","date":"derred"},
            {"title":"http://tombatossals.github.io/angular-leaflet-directive/#!/","description":"dsfd","tagline":"tt","date":"rrere"}
         ];

【讨论】:

  • 我的意思是设置一个指向 .ts 的链接,然后像 从 html 调用
  • link = { title:'terms', link:'#abc'};
  • 更新了检查你自己的应用程序stackblits 导航回stackblits
  • 感谢您的想法,我的最终代码是:
【解决方案2】:

如果我对您的理解正确,您想在您的网站中制作“过滤器”,这是我对此的回答:

简短回答:在 Angular 中使用“点击”方法并在其中调用您的方法

如果这不是你想要的,很抱歉,但它可能会帮助其他人

**更多说明的代码示例:**

//The Shop.Component :
import { Component, OnInit } from '@angular/core';
import { IProduct } from '../shared/models/product';
import { ShopService } from './shop.service';
import { IBrand } from '../shared/models/brand';
import { IType } from '../shared/models/ProductType';

@Component({
  selector: 'app-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.scss'],
})
export class ShopComponent implements OnInit {
  products: IProduct[];
  brands: IBrand[];
  types: IType[];
  brandIdSelected = 0;
  typeIdSelected = 0;

  constructor(private shopService: ShopService) {}

  ngOnInit(): void {
    this.getProducts();
    this.getTypes();
    this.getBrands();
  }

  getProducts() {
    this.shopService.getProducts(this.brandIdSelected, this.typeIdSelected).subscribe(
      (response) => {
        this.products = response.data;
      },
      (error) => {
        console.log(error);
      });
  }

  getBrands() {
    this.shopService.getBrands().subscribe(
      (response) => {
        this.brands = [{id: 0, name: 'All'}, ...response];
      },
      (error) => {
        console.log(error);
      });
  }

  getTypes() {
    this.shopService.getTypes().subscribe(
      (response) => {
        this.types = [{id: 0, name: 'All'}, ...response];
      },
      (error) => {
        console.log(error);
      });
  }

  onBrandSelected(brandId: number) {
    this.brandIdSelected = brandId;
    this.getProducts();
  }

  onTypeSelected(typeId: number) {
    this.typeIdSelected = typeId;
    this.getProducts();
  }

}

//Shop.Service :
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { IPagination } from '../shared/models/pagination';
import { IBrand } from '../shared/models/brand';
import { IType } from '../shared/models/ProductType';

@Injectable({
  providedIn: 'root'
})
export class ShopService {

  baseUrl = 'https://localhost:5001/api/';

  constructor(private http: HttpClient) { }

  getProducts(brandId?: number, typeId?: number) {
    let params = new HttpParams();
    if (brandId) {
      params = params.append('brandId', brandId.toString());
    }
    if (typeId) {
      params = params.append('typeId', typeId.toString());
    }

    return this.http.get<IPagination>(this.baseUrl + 'products', {observe: 'response', params})
      .pipe(
        map(response => {
          return response.body;
        })
      );
  }

  getBrands() {
    return this.http.get<IBrand[]>(this.baseUrl +  'products/brands');
  }

  getTypes() {
    return this.http.get<IType[]>(this.baseUrl +  'products/types');
  }
}

//shop -> html:
<div class="container">
<div class="row">

    <section class="col-3">

        <h5 class="text-warning ml-3 my-3">Sort</h5>
        <select class="custom-select mb-3">
            <option>Alphabetical</option>
            <option>Price : Low to High</option>
            <option>Price : High to Low</option>
        </select>
        
        <h5 class="text-warning ml-3 my-3">Brands</h5>
        <ul class="list-group my-3">
            <li class="list-group-item" 
            *ngFor="let brand of brands"
            [class.active]="brand.id === this.brandIdSelected"
            [value]="brand.id"
            (click)="onBrandSelected(brand.id)"
            >
            
                {{brand.name}}
            </li>
        </ul>

        <h5 class="text-warning ml-3 my-3">Types</h5>
        <ul class="list-group">
            <li class="list-group-item" 
            *ngFor="let type of types"
            [class.active]="type.id === this.typeIdSelected"
            [value]="type.id"
            (click)="onTypeSelected(type.id)"
            >

                {{type.name}}
            </li>
          </ul>
          
    </section>

    <section class="col-9">
        <div class="d-flex justify-content-between align-items-center pb-2">
            <header>
                <span>Showing <strong>10</strong> of <strong>16</strong> Results </span>
            </header>
            <div class="form-inline mt-2">
                <input class="form-control my-2 mt-2" style="width: 300px" placeholder="Search"
                type="text">

                <button class="btn btn-outline-primary ml-2 my-2">Search</button>
                <button class="btn btn-outline-success ml-2 my-2">Reset</button>

            </div>
        </div>

        <div class="row">
            <div class="col-4 mb-2" *ngFor="let item of products">
                <app-product-item [product]="item"></app-product-item>
            </div>
        </div>
    </section>
</div>

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2019-01-06
    • 2014-11-01
    相关资源
    最近更新 更多