【问题标题】:Angular: change text description depending on which element was clickedAngular:根据单击的元素更改文本描述
【发布时间】:2019-07-15 07:37:17
【问题描述】:

我正在使用 mat-grid-list 来显示图标和标题,并带有 *ngfor。单击其中一个元素后,我希望显示该元素的描述(它也在数组中。

我的代码如下所示。

<mat-grid-list cols="3" rowHeight="3:1" *ngIf="router.url === '/'">
  <mat-grid-tile *ngFor="let service of services | slice:0:3; let i=index" (click)="changeState()">
    <i class="material-icons"> {{ service.icon }}</i>
    <p> {{ service.name }} </p>
  </mat-grid-tile>
</mat-grid-list>
<div class="description" [@changeDivSize]=currentState *ngFor="let service of services">
  <p> {{service.description}} </p>
</div>

单击第一个 mat-grid-tile 时我想要实现的目标是显示第一个数组的 {{ service.description }},但我不知道该怎么做。

谢谢

【问题讨论】:

    标签: angular typescript angular-material components


    【解决方案1】:

    (click)="changeState()" 编辑为(click)="changeState(service)"

    然后在您的脚本中,将service 的值复制到另一个变量(比如viewedService

    然后在您的最后一个 div 中将其更改为:

    <div class="description" [@changeDivSize]=currentState *ngIf="viewedService">
      <p> {{viewedService.description}} </p>
    </div>
    

    基本上,如果viewedService 被填充,然后显示该值,您只会弹出最后一个 div。如果用户点击另一个 mat-grid tile,内容将会明显改变。

    希望对您有所帮助(附注:我不确定您使用 @changeDivSize 的目的是什么,因为我对 Angular 的了解并不长)

    【讨论】:

    • 嘿,感谢您的回答,它按预期工作。为了回答您的问题,@changeDivSize 是我在 div 元素上使用的动画触发器,其类为“description”,用于为 div 的打开/关闭设置动画。
    【解决方案2】:

    您可能会尝试将所选服务作为 changeState 的参数发送回控制,然后更改 currentService 的值。

    然后改变

    {{service.description}}

    ->

    {{currentService.description}}

    你可以从最后一个 div 中删除 *ngFor。

    显然 currentService 必须处于控制之中。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-12-27
      • 1970-01-01
      • 2023-03-22
      • 2014-08-10
      • 2019-03-11
      • 2017-05-30
      • 2011-12-21
      • 2018-03-06
      • 1970-01-01
      相关资源
      最近更新 更多