[英]Accessing shared component element in DOM in Angular
共享組件: pro-image
該組件具有 id 為 proImg 的圖像元素
<img id="proImg" src="{{imgPath}}">
imgPath 是 @input 變量。
該組件在多個組件中使用,每個父級將圖像路徑和圖像尺寸傳遞給上面的共享組件。
在這個共享的 component.ts 文件中,我試圖通過 id 訪問<img>
元素以向元素添加一些屬性。 但是,雖然通過 Id 訪問元素,但只有最后一個元素被訪問。
每次在類似於主機選擇器的其他組件中使用此圖像元素時,我都希望它唯一。 請建議我該如何實現。
您的問題是它們都具有相同的id
屬性。 id
應該是唯一的,根據getElementById
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById的 Mozilla 文檔
一種選擇不是使用id
,而是使用ViewChild
來訪問 DOM 元素。
將您的模板更改為此
<img #proImg [src]="imgPath">
在您的組件中,您可以通過以下方式訪問它:
class MyCmponent {
@ViewChild('proImg', {static: true}) proImg: ElementRef;
ngAfterViewInit() {
// you can access the native dom element like this:
this.proImg.nativeElement.style.height = "100px";
this.proImg.nativeElement.style.width = "100px";
}
}
另一種選擇,如果只是設置styles或其他屬性,可以在模板中綁定
<img [src]="imgPath" [ngStyle]="styles" [ngClass]="classes">
零件
class MyComponent {
styles = {
width: "100px",
height: "200px
}
classes = ['class1', 'another-class']
更多關於 ngStyle https://angular.io/api/common/NgStyle
更多關於 ngClass https://angular.io/api/common/NgClass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.