Function called for every event Angular 9

419 Views Asked by At

I'm using lazy loading structure for my angular project. I have using property binding using a function call in my template. The issue is, whenever I click anywhere on page, this function is called. Below I have shared my code.

app-component.html code

<router-outlet></router-outlet> 
<div [style]="hello()">Hello world</div>

app-component.ts code

hello() { 
  console.log('testing>>>>>');   
  return `color:red`; 
}

Each and every time with click event, hello() is called.

Note: When I remove/comment <router-outlet></router-outlet>, it functions normal.

What could be the root cause of this problem. Thanks in Advance.

1

There are 1 best solutions below

5
On

The function is fired on redraw and not the router-outlet. You should avoid using functions in your template. If should be a pure pipe for those cases or bind to variables in your typescript code.

Here i have example where you would get the same issue. It will also fire just by pressing the click button even though nothing happends. It triggers the redraw.

https://stackblitz.com/edit/angular-ivy-9aeje5?file=src%2Fapp%2Fhello.component.ts

hello-component.ts

@Component({
  selector: 'hello',
  template: `<h1 [style]="ohNo()">Hello {{name}}!</h1><button (click)="anyAction()">click</button>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  @Input() name: string;

  ohNo() {
    console.log('i fire on redraw');
    return 'color:red';
  }
  anyAction() {}
}

if you need to change the color via some functionality you can have it bound to a variable

<p [ngStyle]="{
  color: appColor
}">
  Start editing to see some magic happen :)
</p>

and in your code .ts file have

appColor = 'red';