【问题标题】:How to create different template reference variable for items in *ngFor angular如何为 *ngFor angular 中的项目创建不同的模板引用变量
【发布时间】:2018-06-24 03:52:28
【问题描述】:

我有一个按钮属性列表,我希望这些按钮具有不同的模板引用变量,但我使用 *ngFor 渲染它们。如何将引用变量设置为#button1、#button2 等。我需要将模板引用变量设置为该按钮的 ToolTipDirective。

为什么我需要这样做: 在 Firefox 中无法访问按钮的工具提示(使用 TAB 时工具提示不显示)。因此,要显示工具提示,我需要将按钮设为:<button #button1=bs-tooltip (focus)="button1.toggle()" (blur)="button1.toggle()" [tooltip]=button.tooltip" >{{button.text}}</button>。使用相同的模板引用变量会产生一个问题,即当焦点位于另一个按钮上时会显示按钮的工具提示(两个工具提示都会显示,但应该只显示 1 个)。

代码:

<li *ngFor="let button of buttons">
   <button #button1=bs-tooltip (focus)="onFocus(button1) [tooltip]=button.tooltip" >{{button.text}}</button> --> how can I set #button1?
</li>

【问题讨论】:

  • 您的模板看起来正确,应该可以按预期工作。传递给onFocus 的每个变量都将具有对单个按钮的唯一引用。你还在用这个按钮做其他事情吗?
  • 存在onFocus()由于同一个模板引用变量在错误的时间被调用的bug
  • 嗯。尝试传入$event - onFocus($event): angular.io/guide/user-input
  • 它应该适用于同名。你能添加更多代码吗?什么是 ToolTipDirective?
  • 我希望 onFocus 使用该按钮的 ToolTipDirective 执行一些操作,但传递 $event 并不能解决这个问题。我无法从事件中获取 ToolTipDirective。

标签: angular


【解决方案1】:

可以绑定id属性,然后使用document获取html元素

这是一个例子

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  onClick(foo) {
    console.log(foo)
  }

  getElementById(id) {
    return document.getElementById(id);
  }
}

app.component.html

<button (click)="onClick(getElementById('foo'))">click </button>

<input [id]="'foo'">

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 2017-11-10
    • 2018-11-11
    • 2021-08-14
    • 2020-11-29
    • 1970-01-01
    • 2019-05-22
    • 2017-08-02
    相关资源
    最近更新 更多