Angular - Use a default image if image does not exist on server - javascript

I have a component that will display a cover image. The user can upload a cover image and the component will display the user uploaded image. If the user doesn't upload an image, then I want to display a default image.
If there is no user uploaded image I want to return an error and call the changeSource(event), which should in theory bind a new image url to the img src. However I'm getting undefined for the event.target.src and I'm seeing a blank space where the default image should be. It works fine when displaying the custom image.
component.html
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{coverPhoto}}"
(error) ="changeSource($event)" />
</div>
component.ts
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
changeSource(event) {
event.target.src = "https://imageurl";
}

directly use (where defaultImage is a variable in ts file which holds the default image path) -
(error)="$event.target.src = defaultImage"
your HTML -
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{ coverPhoto }}" (error)="$event.target.src = defaultImage" />
</div>
Working example here.
You are passing event from this code in ts, which is obviously undefined, and you don't need to call this function from here -
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);

The *ngFor was throwing it off. Removing this seemed to solve the problem. Not quite sure why so will post an edit when I discover why.
<div>
<img src="{{coverPhotos}}"
(error)="$event.target.src = defaultImage" />
</div>

Related

why image doesn't show up

I'm trying to feed image path through property path and render it. I have many images and I want to set the image in runtime so I cannot use pre import the image prior to rendering. But the image does not show.
Error: cannot find module (but path is correct)
but when I replace the varible path to actual path as var imageName = require('./Assets/profpicjpg.jpg').default; then image shows up, but I wanna use the variable path to feed the variable path data
Rendering this
import Profpic1 from './Components/Public-page/Profile-card';
function App() {
return (
<div className="App">
<Profpic1
path = './Assets/profpicjpg.jpg'
/>
</div>
)
}
export default App;
Function (this is in a different page)
export default function Profpic1 ({path})
{
var imageName = require(path).default;
return (
<div>
<img src={imageName} />
</div>
)}

React.js Previewing an Image with input type file

Currently I am trying to preview an image up on an upload of an image file. I can recieve the image, and console log however I can not display it in the img tag.
Here is the way that I am trying to render them:
<input type='file' id="uploadImage" onChange={this.handleImageChange} className="upload-input" />
<label htmlFor="uploadImage" className="upload-image-button">Choose An Image</label>
{this.state.imagePreview[0] ?
<img src={this.state.imagePreview[0]} alt="" className="image-preview" />
:
<img alt="" className="image-preview" />
}
Here are my state and my handle on change method for the input:
state = {
imagePreview: {}
}
handleImageChange = async (e) => {
console.log(e.target.files)
await this.setState({ imagePreview: e.target.files })
console.log(this.state.imagePreview)
}
Here are my console logs for the files:
You'll need to use a FileReader object, in order to get the base64 data and apply it to the source of the image tag.
Also, I don't see any need for this to be an async function (unless, for the sake of brevity, you left out a promise you're working with).
From the code you've presented, something like this should work:
handleImageChange(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(event) {
// The file's text will be printed here, if you want to see the base64
console.log(event.target.result)
// Set state with base64 data
this.setState({ imagePreview: e.target.result })
};
reader.readAsText(file);
}
Html (or jsx) would look something like so:
<img src={this.state.imagePreview} alt="" className="image-preview" />

Using an imported image based on json data character name

I am getting data from a json file and when I get the character name of the object i'd like the div to render an image from an image I had imported. But when I use src={char} and say for example the char from the json file is 'sage' i'd like to use the sage image. But doing this method does not work like that. Also I am successfully getting the data from the json file so no problems on that end.
Thanks!
import sage from '../../assets/images/agents/sage_thumb.webp';
import viper from '../../assets/images/agents/viper_thumb.webp';
import jett from '../../assets/images/agents/jett_thumb.webp';
import valorant_rank from '../../assets/images/ranks/valorant.png';
const renderBody = () => {
return matchData && matchData.map(({ id, char, name, roundsPlayed, performance, multiKills, team }) => {
return (
<tr key={id} className='tr-background'>
<td className='match-table__agent-cell'><img className='img-fluid' src={char} alt="" /></td>
</tr>
)
})
}
I would use an object to map the agent name to its image url
const imageByAgent = {
sage: "../../assets/images/agents/sage_thumb.webp",
viper: "../../assets/images/agents/viper_thumb.webp",
...
}
And for the image src you can fetch the url using the character name
<img className='img-fluid' src={imageByAgent[char]} alt="" />

Modify Image Url Value with Vue Js in a Loop

I have a simple Loop with conditionals. I want to modify the full url to a version of the image with 60x60 pixels.
Full image url : www.example.com/img/full-image-001.jpg .
Modified image url that I need : www.example.com/img/full-image-001-60x60.jpg .
<template v-else-if="column === 'product_img'">
<img :src="replaceLink.columnValue" alt="" height="60" width="60">
</template>
Method function:
methods : {
replaceLink (record) { //logic
}
}
EDIT :
Is this the proper way ?
methods: {
replaceLink (record) {
let res = record.replace(".jpg", "-60x60.jpg");
console.log(res);
}
},
Better solution is to create filter and use it on your images.
Instead fo methods object create filters object with replace function:
filters: {
replaceLink: function(value) {
if (!value) return '';
return value.replace('.jpg', '-60x60.jpg');
}
}
And now in your HTML you can use it like this:
<img :src="source | replaceLink" />
You should have source in your component data or you will get an error. This source should be image url

Read-only variable when assigning object to variable

I have a variable named picture that is taking in a thumbnail that is an address for a picture. I want to use that as the src path for my img tag. How do I accomplish this? From what i'm understanding is React generates render() first and then componentDidMount(), but my code is returning Cannot set property 'src' of null.
Update
I changed the code based off suggested comments. I loaded the state in my constructor so that gets defined before everything else. But now it says picture" is read-only which is where --> is
Code
constructor(props) {
super(props);
this.props.getVideos();
const picture = {};
this.props.getVideos();
if (this.props.videos == null) {
console.log("It's null");
} else {
const videos = this.props.videos.video.map(video => {
<h5 key={video._id}>{video.thumbnail}</h5>;
--> picture = video.thumbnail;
});
}
}
componentDidMount() {
console.log(picture);
}
Snippet of return in render
<div className="explore">
<div className="row">
<div className="row__inner">
<div className="tile">
<div className="tile__media">
<img className="tile__img" id="thumbnail" src={picture} alt="" />
</div>
<div className="tile__details">
<div className="tile__title">
<h5>Impact Dallas</h5>
</div>
</div>
</div>
Update
I changed the code based off suggested comments. I loaded the state in my constructor so that gets defined before everything else. But now it says picture" is read-only which is where --> is

Categories