Search code examples
angularonerror

calling a function onerror of img src


This is my code in angular 2:

test.component.html:
<img src="./assets/sample.jpeg" onError="setValue()">
{{imageMenu}}

test.component.ts:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
imageMenu:boolean = true;
  constructor() { }
  ngOnInit() {

  }
  setValue():void{
    alert("hi");
    this.imageMenu = !this.imageMenu;
  } 
}

My question is when the image source is empty, even then the Boolean value is true. setValue() is not getting called on error. Pls guys help me to resolve this. I am new to angular.


Solution

  • When you are using HTML DOM events in Angular remove the on prefix from the event and use it. ex

    onclick ---> (click)

    use (error) instead of onError

    <img src="assets/sample.jpeg" (error)="setValue()">