如何使用角度2或4或5中的name属性获取dom元素

时间:2018-05-02 06:27:46

标签: angular typescript angular5 angular2-template

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

HTML code:

<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;
  }
});
}

1 个答案:

答案 0 :(得分:1)

您可以通过创建directive并附加您的元素来获取访问权限,下面是代码,下面的指令使用ElementRef,其中inturn允许您与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;
  }
}

Component.ts

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

Component.html

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