【问题标题】:Find an element by its id in the html file在 html 文件中通过 id 查找元素
【发布时间】:2021-01-12 18:33:55
【问题描述】:

我有一个数组

items = [{
"id" : 1,
"name": "peter"},
{
"id" : 2,
"name": "john"}
    ...
]

我试图根据 id 在 html 文件中找到一个项目,我试图隐藏和元素。

在js文件中可以很容易地完成,但我想看看是否有一种简单的方法可以在html文件中完成

【问题讨论】:

  • 你的问题不是特别清楚。如果您想知道对象字面量的 id 属性是否映射到 html 元素的 id 属性,答案只有在您已采取措施实现这一点的情况下。
  • 您可以创建一个表。例如有 2 列的表。第一列包含 id,第二列包含名称。从表中搜索项目后。
  • @TheHeadRush 我正在尝试类似
    在 items 数组中,我想看看 id ==1 那么名字应该是peter。

标签: javascript angular lodash angular8


【解决方案1】:

如果你想隐藏一个项目,假设它的索引是 2,你可以在 HTML 中做这样的事情

<ng-container *ngFor="let eachItem of allArrayItems; let index=i">
  <div *ngIf="i != 2">  // This ngIf will be hidden if the index is 2
     whatever logic
  </div>
</ng-container>

【讨论】:

    【解决方案2】:

    你可以给元素添加一个模板选择器

    <input #myElement>
    

    然后您可以在您的ts 文件中添加引用

    @ViewChild('myElement') myInput: ElementRef<HtmlInputElement>;
    

    甚至直接在模板中引用元素

    <button (click)="myElement.focus()"></button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2021-12-23
      • 2017-05-02
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多