I have a basic image
component and within it there is an img
element. Is there a way to pass the native img
attributes to image
without having to define them all, such as alt
and have them all applied to the img
tag?
Here is some pseudo code of what I mean:
@Component({
selector: 'image',
template: '<img [src]="src" [...attrs]>'
})
export class ImageComponent {
@Input() attrs;
}
<image img.alt="Some Alternative Value">
<another-component></another-component>
</image>
CodePudding user response:
As far as I'm aware of, it is not possible to reflect attributes from the component host into the component view, without having to manually define @Input()
s for every possible attributes.
An possible alternative, if it applies to you, is to project an img
element from outside your image
component, inside the component's view.
<image>
<img alt="Some Alternative Value">
<another-component></another-component>
</image>
That way, you basically have the img
element exposed, where you can freely add attributes, among others.
CodePudding user response:
Yeah, this can be done (if it's what you're after ..)
@Component({
selector: 'image',
template: '<img #imgRef [src]="src">'
})
export class ImageComponent {
@ViewChild('imgRef') imgRef: ElementRef<HtmlElement>;
@Input() attrs;
ngAfterViewInit() {
// assuming attrs is a key/value object
Object.entries(this.attrs).forEach(([key, value]) => {
this.imgRef.nativeElement.setAttribute(....)
})
}
}