Is there a way to dynamically set the src
attribute of an <img>
tag in an HTML file using a string path from a file?
The path is retrieved from the cordova.file.dataDirectory
Cordova plugin within Ionic2
(TypeScript
) and it typically looks like this:
UPDATED TO DISPLAY MY CODE:
This snippet shows the relevant section of the profile.ts code
...
import {Camera} from "ionic-native";
...
import {API} from "../../services/api";
import {ImageAdquistionService} from "../../services/imageAdquisition.service";
...
import {Network,File} from 'ionic-native';
declare let cordova: any;
@Component({
selector: 'page-profile',
templateUrl: 'profile.html'
})
export class ProfilePage implements OnInit{
connected:boolean = false;
imagePath: string = "./assets/img/pio.jpg";
userInfo: User = new User();
constructor(
private api:API,
private imageAdquistionService: ImageAdquistionService,
){
//seleted tab by default
this.tabs="info";
this.connected = Network.type !== "none";
}
ngOnInit(): void {
this.localStorageService.getUserInfo().then(user => {
this.userInfo = user;
if (this.userInfo.imagenPerfil !== "defAlert") {
File.checkFile(cordova.file.dataDirectory,this.userInfo.profileImage).then(result => {
console.log("exist")
this.imagePath = cordova.file.dataDirectory + this.userInfo.profileImage;
})
.catch(error => {
console.log("not exist " + JSON.stringify(error))
})
}
});
}
/* The rest of the code remains the same */
}
This part showcases the key points of the imageAdquisitionService code
/* The imageAdquistionService code block */
This excerpt demonstrates the essential aspects of the API service code
/* The api service code block */
Lastly, here is the pertinent snippet of the HTML code
<ion-item no-lines class="item-bar-profile">
<ion-avatar>
<img class="centered" src="imagePath" (click)="presentOptions();">
</ion-avatar>
</ion-item>
This example uses a hardcoded default image path:
this.imagepath = "./assets/img/pio.jpg"
https://i.sstatic.net/tLsV5.png
Here's what happens when programmatically changing the path:
this.imagepath = file:///data/user/0/com.ionicframework.myionicproject494629/files/58db7e92be26f32d4c8c01d2_1491989021049.jpg
https://i.sstatic.net/LS9sW.png
Thank you!