I've tried all the possible means of loading images into a template.html in a rails/angular application but none of my methods are working.
I imported my template file - import template from "./template.html";
Here's what my angular component looks like
import { Component } from '@angular/core';
import template from "./template.html";
import logo from "../packs/img/logo.png";
@Component({
selector: 'ms-nav',
template: template
})
export class NavComponent {}
Here is the list of variants I've tried. Where logo.png is saved in /assets/images/logo.png i also saved the same logo in packs/img/logo.png just to see which one would eventually work.
<img src="/assets/images/logo.png" alt="" /> got this error in console GET http://localhost:5000/assets/images/logo.png 404 (Not Found)
<img src="<%= asset_pack_path 'logo.png' %>" alt="" /> got this error in console GET http://localhost:5000/%3C%=%20asset_pack_path%20'logo.png'%20%%3E 404 (Not Found)
<img src="<%= asset_pack_path '/img/logo.png' %>" alt="" /> - GET http://localhost:5000/%3C%=%20asset_pack_path%20'img/logo.png'%20%%3E 404 (Not Found)
<img src="<%= image_tag('logo.png') %>" alt="" /> - GET http://localhost:5000/%3C%=%20image_tag('logo.png')%20%%3E 404 (Not Found)
I even tried importing logo as well but got this error - template.html?6163:1 Uncaught Error: Cannot find module "./logo"
I'm not sure if this is wrong, but I think this might be happening because of
// app/javascript/hello_angular/html.d.ts
declare module "*.html" {
const content: string
export default content
}
As per the documentation, this is supposed to tell typescript not to do anything with an html file whenever it comes across it. So since typescript is treating all content in this file as a string, how are we suppose to load images through an external template file?
I basically ran out of variants on the possible methods to load image through a template.html file.
Any help or suggestions would be appreciated.
Thank you.
@mayordwells Have you found solution for this?
No I haven't. I'm just using Cloudinary to upload images for now. Images still won't load from template files in Angular.
@mayordwells Could you try the following sample? It works for me.
You can also move declare function require(path: string); to your *.d.ts file (but I didn't try),
declare function require(path: string);
import { Component } from '@angular/core';
@Component({
selector: 'hello-angular',
template: `
<h1>Hello {{name}}</h1>
<img src="{{imageSrc}}" />
`
})
export class AppComponent {
name = 'Angular!';
imageSrc = require('./logo.jpg');
}
@josephMG Thanks, I'll give this a try.
Thanks, I don't know why but It works
Most helpful comment
@mayordwells Could you try the following sample? It works for me.
You can also move
declare function require(path: string);to your *.d.ts file (but I didn't try),