У меня есть шаблон, в котором есть несколько тегов изображений (img), все они повторяются в цикле foreach и изменяют этот атрибут / свойства 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.info('inside getIcon:img', img);
if (img) {
img['src'] = imageUrl;
}
});
}
это сработало для вас ???
вы можете получить доступ, создав 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;
}
}
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>
Без использования document.querySelector или document.getElementByName и т. д. Возможно ли это с любой функцией Angular, такой как ElementREf и т. д.