0

Shared component: pro-image

This component has image element with id proImg

<img id="proImg" src="{{imgPath}}">

imgPath is @input variable.

This component is used in multiple components and each parent passes image path and image dimension to above shared component.

In this shared component.ts file, I'm trying to access <img> element by id to add some attributes to the element. But while access element by Id only last element is getting accessed.

I want to uniquely this image element each time its been used in other component similar to host selector. Please suggest how can I achieve.

1 Answer 1

1

Your issue is that they all have the same id property. id should be unique, per Mozilla docs for getElementById https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

One option, instead of using the id, use a ViewChild to access the DOM Element.

Change your template to this

<img #proImg [src]="imgPath">

And in your component you can access it this way:

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


Another option, if you are just setting styles or other properties, you can bind them in the template

<img [src]="imgPath" [ngStyle]="styles" [ngClass]="classes">

Component

class MyComponent {

styles = { 
    width: "100px",
    height: "200px
}

classes = ['class1', 'another-class']

More on ngStyle https://angular.io/api/common/NgStyle

More on ngClass https://angular.io/api/common/NgClass

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.