【问题标题】:How to get dom element using name attribute in angular 2 or 4 or 5如何使用角度 2 或 4 或 5 中的名称属性获取 dom 元素
【发布时间】:2018-05-02 06:27:46
【问题描述】:

我有一个模板,里面有多个图像(img)标签,所有这些都在 foreach 循环中迭代并在 typescript 文件中修改这个 img src 属性/属性。

HTML 代码:

<div *ngFor="let lt of list">
<div>
    <a href="{{lt.url}}" target="_self">
      <img mat-card-image name="{{lt.name}}" class="image" src="" placement="top" container="body">
    </a>
</div>
<div>
    <a href="{{lt.url}}" target="_self">
      <img mat-card-image name="{{lt.name}}" class="image" src="" placement="top" container="body">
    </a>
</div>
<div>
    <a href="{{lt.url}}" target="_self">
      <img mat-card-image name="{{lt.name}}" class="image" src="" placement="top" container="body">
    </a>
</div>
</div>

打字稿文件中的代码,

ngOnInit() {
    for (const lt of list) {
        if (lt.title === 'xyz') {
          lt.title = 'XYZ';
        }
        if (lt.appFlag) {
          this.getIcon(lt.name);
        }
    }
}


  private getIcon(name: string): void {
  const imageUrl = this.service.createURL('abc');

  // how to get img tag using property/attribute name(name here is unique item name) from HTML without using document.querySelector etc.
  ....
  ....
  //const img = this.name.nativeElement.name;

  //console.log('inside getIcon:img', img);


  if (img) {
    img['src'] = imageUrl;
  }
});
}

【问题讨论】:

  • 不使用 document.querySelector 或 document.getElementByName 等,是否可以使用 ElementREf 等任何 Angular 功能
  • 这对你有用吗???

标签: angular typescript angular5 angular2-template


【解决方案1】:

您可以通过创建directive 并附加您的元素来获得访问权限,下面是代码,下面的指令使用ElementRef,这反过来又允许您与nativeHtml 元素进行交互。


ImageElementDirective

import { ElementRef } from '@angular/core';
import { Directive } from '@angular/core';

@Directive({
  selector:"[imageElement]"
})
class ImageElement {
  constructor(private el: ElementRef) {
  }

  getImage() : any {
    return el.nativeElement;
  }
}

组件.ts

//this will give you all image element , 
//you should use for loop or foreach to perform operation 
//you want
@ViewChildren(ImageElement) allImageElement; 

组件.html

<img imageElement ..rest>
<img imageElement ..rest>

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 2023-03-09
    • 2018-10-21
    • 2011-12-28
    • 2011-10-10
    • 1970-01-01
    • 2021-03-23
    • 2019-05-21
    相关资源
    最近更新 更多