【问题标题】:How to generate different routerLinks from ngFor created items?如何从 ngFor 创建的项目生成不同的 routerLinks?
【发布时间】:2019-05-22 17:58:10
【问题描述】:

我正在使用 ngFor(在“列表组件”中)来显示几个“项目组件”,并且我想在用户单击其中一个项目时将其发送到“项目详细信息组件” .

问题是我仍然是 Angular 的早期学习者,我不明白那些在我脑海中甚至不存在的 routerLink 背后的逻辑。

我尝试使用 let i = index 获取我的项目的“id”,但在这一步之后我不知道如何处理 i。

有人可以帮我解决这个问题吗?非常感谢!

liste-actus HTML

<div class="container list-group">
  <a *ngFor="let actu of actus | async; let i = index" class="list-group-item list-group-item-action flex-column align-items-start" routerLink="">
     <app-item-actus [actu]="actu"></app-item-actus>
  </a>
  <br>
</div>

liste-actus TS

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';

import { ActuService } from 'src/app/services/actu.service';
import { Actu } from 'src/app/modeles/actu';

@Component({
    selector: 'app-liste-actus',
    templateUrl: './liste-actus.component.html',
    styleUrls: ['./liste-actus.component.css']
})

export class ListeActusComponent implements OnInit {

    actus: Observable<Actu[]>;

    constructor(private actuService: ActuService, private route: ActivatedRoute) { 
    }

    ngOnInit() {
        this.actus = this.actuService.getActusList();
    }

}

【问题讨论】:

    标签: angular routing routes ngfor routerlink


    【解决方案1】:

    除了routerLinkid 部分之外,一切似乎都很好。

    您的Actu 类是否有id 属性?如果是,那么您可以在routerLink 中使用actu.id

    所以a 标签应该是这样的:

    <a *ngFor="let actu of actus | async;" [routerLink]="['path/of/your/route', actu.id]"
     /*other stuff*/ 
    >
         <app-item-actus [actu]="actu"></app-item-actus>
    </a>
    

    请注意,routerLink 在方括号中 ([routerLink])。这样,您可以将变量绑定到属性。如果不是,则放入属性中的值只是一个字符串。

    如果您的Actu 类没有id 属性并且您想使用索引作为id,那么您应该使用它。

    <a *ngFor="let actu of actus | async; let i = index" [routerLink]="['path/of/your/route', i]"
     /*other stuff*/ 
    >
         <app-item-actus [actu]="actu"></app-item-actus>
    </a>
    

    【讨论】:

    • 谢谢,这段代码使用了你刚刚展示给我的语法!我遇到了另一个问题:我必须在app-actu-detail 中使用actu 的属性。看来我无法像使用&lt;app-item-actus [actu]="actu"&gt;&lt;/app-item-actus&gt; 那样将有关actu 的信息发送到另一个组件。我试过这个&lt;app-item-actus [actu]="actu"&gt;&lt;/app-item-actus&gt; &lt;app-actu-detail [actu]="actu" class="hide"&gt;&lt;/app-actu-detail&gt; 但我得到这个错误:错误类型错误:无法读取 Object.eval [as updateDirectives] 处未定义的属性“标题”
    • 我不能说什么,因为我不知道app-actu-detail组件的内容或组件之间的交互。请通过 stackblitz 分享您的代码,以便我进一步帮助您。
    • 你可以在这里找到我项目的所有 Angular 代码 stackblitz.com/github/Adopt1Projet/AdoptUnStage 在 stackblitz 上似乎不起作用,但你可以从这里检查所有内容 :) 我们正在讨论的组件在 Router/PageActus 中。
    • 我会看看并尝试弄清楚。
    • 我用你的代码创建了一个新项目here。我发现了 3 个主要问题。首先,您应该使用像../../actu 这样的相对路径而不是src/app/actu 导入。其次,您可以使用类型而不是 any,例如 actus: anyactus: Observable&lt;Actu[]&gt;。我建议您将 http 结果转换为类型。向组件发送未触及的 http 响应可能会导致意外行为。
    猜你喜欢
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多