Angular2 - infinite loop when i call method from Angular 2 class inside template

I have a problem when I call the method from a component in a template by interpolation: {{get_method()}}

. The method works, but in an infinite loop, I don't know why. Any help please ??

the method code looks like this:

get_name() {
  console.log("bonjour");
}

      

and I call it in my template like this:

{{get_name()}}

      

and this is the result:

enter image description here

+4


source to share


4 answers


Finally I found a solution to change the detection strategy for OnPush for more information. Review this link Change detection strategy: OnPush



+1


source


You shouldn't use methods in your template, because every time Angular triggers change detection, the method will be called, which can happen often. So it's not really an infinite loop, the method is simply called whenever a change is detected.



To avoid this, you need to change your code to handle method logic in your component and use variables in your template instead.

+14


source


In your component

getName:string;
ngOnInit() {
   this.get_name();
}
get_name() {
    console.log("bonjour");
    this.getName = "bonjour";
}

      

And in your view file

{{getName}}

      

0


source


I have same problem on my angular 6 project. this is my code.

  <div *ngFor="let menu of MenuList"> 
     <span>{{bindMenuNames(menu.FullNameSpace)}}</span> 
  </div>

 bindMenuNames(FullNameSpace): string {
        console.log(FullNameSpace);
        let menuname: string;
        switch (FullNameSpace)
        {
            case "Message_Centrel":
                menuname = "Messaging";
                break;

            case "Admin":
                menuname = "Admin"
                break;
            case "Catalog":
                menuname = "Course Authoring"
                break;
}
}


  [1]: https://i.stack.imgur.com/ngJ4Y.png

      

0


source







All Articles