How many time ngStyle is applied












2















I am applying color to div element and i am changing color in cycle as follow



 toogleColor()


{



if(this.color=='blue')
{
this.color="red"
this.fontcolor='white'
return
}else if(this.color=='red'){
this.color='white'
this.fontcolor='black'
return
}else if(this.color=='white'){
this.color='blue'
this.fontcolor='white'
return
}


}



and I have setStyle() function as follow:



  setStyle(){
this.toogleColor()
return {

'background-color':this.color,
'height':'382px'
}


}



In my component html I binded style as follow:



<div  [ngStyle]="setStyle()"  *ngFor="let element of array1">


But i am not Getting expected color cycle because setStyle() funnction is called 4*number of element in array










share|improve this question


















  • 2





    What is your exact need? Describe it in details so we may come up with a different solution. Because of Angular's ChangeDetection it is really bad idea to call a method from markup. Also, setStyle method is called way more times than you think.

    – Bunyamin Coskuner
    Nov 15 '18 at 7:58


















2















I am applying color to div element and i am changing color in cycle as follow



 toogleColor()


{



if(this.color=='blue')
{
this.color="red"
this.fontcolor='white'
return
}else if(this.color=='red'){
this.color='white'
this.fontcolor='black'
return
}else if(this.color=='white'){
this.color='blue'
this.fontcolor='white'
return
}


}



and I have setStyle() function as follow:



  setStyle(){
this.toogleColor()
return {

'background-color':this.color,
'height':'382px'
}


}



In my component html I binded style as follow:



<div  [ngStyle]="setStyle()"  *ngFor="let element of array1">


But i am not Getting expected color cycle because setStyle() funnction is called 4*number of element in array










share|improve this question


















  • 2





    What is your exact need? Describe it in details so we may come up with a different solution. Because of Angular's ChangeDetection it is really bad idea to call a method from markup. Also, setStyle method is called way more times than you think.

    – Bunyamin Coskuner
    Nov 15 '18 at 7:58
















2












2








2








I am applying color to div element and i am changing color in cycle as follow



 toogleColor()


{



if(this.color=='blue')
{
this.color="red"
this.fontcolor='white'
return
}else if(this.color=='red'){
this.color='white'
this.fontcolor='black'
return
}else if(this.color=='white'){
this.color='blue'
this.fontcolor='white'
return
}


}



and I have setStyle() function as follow:



  setStyle(){
this.toogleColor()
return {

'background-color':this.color,
'height':'382px'
}


}



In my component html I binded style as follow:



<div  [ngStyle]="setStyle()"  *ngFor="let element of array1">


But i am not Getting expected color cycle because setStyle() funnction is called 4*number of element in array










share|improve this question














I am applying color to div element and i am changing color in cycle as follow



 toogleColor()


{



if(this.color=='blue')
{
this.color="red"
this.fontcolor='white'
return
}else if(this.color=='red'){
this.color='white'
this.fontcolor='black'
return
}else if(this.color=='white'){
this.color='blue'
this.fontcolor='white'
return
}


}



and I have setStyle() function as follow:



  setStyle(){
this.toogleColor()
return {

'background-color':this.color,
'height':'382px'
}


}



In my component html I binded style as follow:



<div  [ngStyle]="setStyle()"  *ngFor="let element of array1">


But i am not Getting expected color cycle because setStyle() funnction is called 4*number of element in array







css angular html5 angular6






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 7:38









N KN K

325




325








  • 2





    What is your exact need? Describe it in details so we may come up with a different solution. Because of Angular's ChangeDetection it is really bad idea to call a method from markup. Also, setStyle method is called way more times than you think.

    – Bunyamin Coskuner
    Nov 15 '18 at 7:58
















  • 2





    What is your exact need? Describe it in details so we may come up with a different solution. Because of Angular's ChangeDetection it is really bad idea to call a method from markup. Also, setStyle method is called way more times than you think.

    – Bunyamin Coskuner
    Nov 15 '18 at 7:58










2




2





What is your exact need? Describe it in details so we may come up with a different solution. Because of Angular's ChangeDetection it is really bad idea to call a method from markup. Also, setStyle method is called way more times than you think.

– Bunyamin Coskuner
Nov 15 '18 at 7:58







What is your exact need? Describe it in details so we may come up with a different solution. Because of Angular's ChangeDetection it is really bad idea to call a method from markup. Also, setStyle method is called way more times than you think.

– Bunyamin Coskuner
Nov 15 '18 at 7:58














3 Answers
3






active

oldest

votes


















1














Let's talk about couple of things wrong about your code.





  1. setStyle is confusing method and does two things at the same time. It, indeed, sets something but also returns a value. It is against Single Responsibility Principle and also confuses the person who takes a look at the html first. So, when I see [ngStyle]="setStyle()", I would think there is something wrong with this code, because in general setters do not return anything.

  2. You call a method from html which will result in unpredicted behaviour like the one you are having right now. It is because, Angular has this concept called Change Detection If you haven't heard of it, you should read about it. In short, whenever an event (user click, xhr request etc.) is triggered, Angular goes through your html and your component to detect if something has changed. While doing so, if there is a method within your html, angular will call it to get the result value to do some checks which may be OK for some cases if the called method does not do anything super complicated and finishes very quickly. However, with your case, it does something, it changes the color.


So, what can we do?



We need to seperate the logic of setting colors and getting colors into two different methods. Also, if possible, we should avoid calling methods from html.



I think what you are trying to do is to assign different colors to each element of the array based on previous element's color. So you can do something like following



@Component({
selector: 'demo',
template: `
<div [ngStyle]="element.style" *ngFor="let element of array1"></div>
`
})
export class DemoComponent implements OnInit {

array1 = ;

color = 'white';

constructor() { }

ngOnInit() {
// get array from somewhere
// this.array1 =

this.array1.forEach(element => {
const colorConfig = this.getNextColor();
element.style = {
'background-color': colorConfig.color,
'height': '382px',
'color': colorConfig.fontColor
};
});
}

getNextColor() {
let fontColor;
if (this.color === 'blue') {
this.color = 'red';
fontColor = 'white';
} else if (this.color === 'red') {
this.color = 'white';
fontColor = 'black';
} else if (this.color === 'white') {
this.color = 'blue';
fontColor = 'white';
}

return {
color: this.color,
fontColor: fontColor
};
}

}





share|improve this answer

































    0














    Yes, it will call multiple times since you have used *ngFor and it will create multiple div element and multiple div will call ngStyle multiple times.



    If you wan to call it once then you can wrap it like



    <div  [ngStyle]="setStyle()">
    <ng-container *ngFor="let element of array1">
    ....
    </ng-container>
    </div>


    If you want to apply the ngStyle in the same div and want to repeat the same then you should put this setStyle into some variable in use it as -



    public style;

    ngOnInit(){
    this.style = this.setStyle(); //return the styles
    }


    <div [ngStyle]="style" *ngFor="let element of array1">





    share|improve this answer































      0














      It 's better in your case to use ngClass instead of ngStyle and I don't think you need to use function at all.



      style



      .blue {
      color:blue;
      background-color:red; // many css property
      }

      .red {
      color:red;
      ...
      }

      .white {
      color:white
      ...
      }


      template



      <div  [ngClass]="color" *ngFor="let element of array1" >


      the class can have another property but if you still only changeing just the color you can use ngStyle



      <div  [ngStyle]="{color:color}" *ngFor="let element of array1" >


      stackblitz demo






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53314500%2fhow-many-time-ngstyle-is-applied%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Let's talk about couple of things wrong about your code.





        1. setStyle is confusing method and does two things at the same time. It, indeed, sets something but also returns a value. It is against Single Responsibility Principle and also confuses the person who takes a look at the html first. So, when I see [ngStyle]="setStyle()", I would think there is something wrong with this code, because in general setters do not return anything.

        2. You call a method from html which will result in unpredicted behaviour like the one you are having right now. It is because, Angular has this concept called Change Detection If you haven't heard of it, you should read about it. In short, whenever an event (user click, xhr request etc.) is triggered, Angular goes through your html and your component to detect if something has changed. While doing so, if there is a method within your html, angular will call it to get the result value to do some checks which may be OK for some cases if the called method does not do anything super complicated and finishes very quickly. However, with your case, it does something, it changes the color.


        So, what can we do?



        We need to seperate the logic of setting colors and getting colors into two different methods. Also, if possible, we should avoid calling methods from html.



        I think what you are trying to do is to assign different colors to each element of the array based on previous element's color. So you can do something like following



        @Component({
        selector: 'demo',
        template: `
        <div [ngStyle]="element.style" *ngFor="let element of array1"></div>
        `
        })
        export class DemoComponent implements OnInit {

        array1 = ;

        color = 'white';

        constructor() { }

        ngOnInit() {
        // get array from somewhere
        // this.array1 =

        this.array1.forEach(element => {
        const colorConfig = this.getNextColor();
        element.style = {
        'background-color': colorConfig.color,
        'height': '382px',
        'color': colorConfig.fontColor
        };
        });
        }

        getNextColor() {
        let fontColor;
        if (this.color === 'blue') {
        this.color = 'red';
        fontColor = 'white';
        } else if (this.color === 'red') {
        this.color = 'white';
        fontColor = 'black';
        } else if (this.color === 'white') {
        this.color = 'blue';
        fontColor = 'white';
        }

        return {
        color: this.color,
        fontColor: fontColor
        };
        }

        }





        share|improve this answer






























          1














          Let's talk about couple of things wrong about your code.





          1. setStyle is confusing method and does two things at the same time. It, indeed, sets something but also returns a value. It is against Single Responsibility Principle and also confuses the person who takes a look at the html first. So, when I see [ngStyle]="setStyle()", I would think there is something wrong with this code, because in general setters do not return anything.

          2. You call a method from html which will result in unpredicted behaviour like the one you are having right now. It is because, Angular has this concept called Change Detection If you haven't heard of it, you should read about it. In short, whenever an event (user click, xhr request etc.) is triggered, Angular goes through your html and your component to detect if something has changed. While doing so, if there is a method within your html, angular will call it to get the result value to do some checks which may be OK for some cases if the called method does not do anything super complicated and finishes very quickly. However, with your case, it does something, it changes the color.


          So, what can we do?



          We need to seperate the logic of setting colors and getting colors into two different methods. Also, if possible, we should avoid calling methods from html.



          I think what you are trying to do is to assign different colors to each element of the array based on previous element's color. So you can do something like following



          @Component({
          selector: 'demo',
          template: `
          <div [ngStyle]="element.style" *ngFor="let element of array1"></div>
          `
          })
          export class DemoComponent implements OnInit {

          array1 = ;

          color = 'white';

          constructor() { }

          ngOnInit() {
          // get array from somewhere
          // this.array1 =

          this.array1.forEach(element => {
          const colorConfig = this.getNextColor();
          element.style = {
          'background-color': colorConfig.color,
          'height': '382px',
          'color': colorConfig.fontColor
          };
          });
          }

          getNextColor() {
          let fontColor;
          if (this.color === 'blue') {
          this.color = 'red';
          fontColor = 'white';
          } else if (this.color === 'red') {
          this.color = 'white';
          fontColor = 'black';
          } else if (this.color === 'white') {
          this.color = 'blue';
          fontColor = 'white';
          }

          return {
          color: this.color,
          fontColor: fontColor
          };
          }

          }





          share|improve this answer




























            1












            1








            1







            Let's talk about couple of things wrong about your code.





            1. setStyle is confusing method and does two things at the same time. It, indeed, sets something but also returns a value. It is against Single Responsibility Principle and also confuses the person who takes a look at the html first. So, when I see [ngStyle]="setStyle()", I would think there is something wrong with this code, because in general setters do not return anything.

            2. You call a method from html which will result in unpredicted behaviour like the one you are having right now. It is because, Angular has this concept called Change Detection If you haven't heard of it, you should read about it. In short, whenever an event (user click, xhr request etc.) is triggered, Angular goes through your html and your component to detect if something has changed. While doing so, if there is a method within your html, angular will call it to get the result value to do some checks which may be OK for some cases if the called method does not do anything super complicated and finishes very quickly. However, with your case, it does something, it changes the color.


            So, what can we do?



            We need to seperate the logic of setting colors and getting colors into two different methods. Also, if possible, we should avoid calling methods from html.



            I think what you are trying to do is to assign different colors to each element of the array based on previous element's color. So you can do something like following



            @Component({
            selector: 'demo',
            template: `
            <div [ngStyle]="element.style" *ngFor="let element of array1"></div>
            `
            })
            export class DemoComponent implements OnInit {

            array1 = ;

            color = 'white';

            constructor() { }

            ngOnInit() {
            // get array from somewhere
            // this.array1 =

            this.array1.forEach(element => {
            const colorConfig = this.getNextColor();
            element.style = {
            'background-color': colorConfig.color,
            'height': '382px',
            'color': colorConfig.fontColor
            };
            });
            }

            getNextColor() {
            let fontColor;
            if (this.color === 'blue') {
            this.color = 'red';
            fontColor = 'white';
            } else if (this.color === 'red') {
            this.color = 'white';
            fontColor = 'black';
            } else if (this.color === 'white') {
            this.color = 'blue';
            fontColor = 'white';
            }

            return {
            color: this.color,
            fontColor: fontColor
            };
            }

            }





            share|improve this answer















            Let's talk about couple of things wrong about your code.





            1. setStyle is confusing method and does two things at the same time. It, indeed, sets something but also returns a value. It is against Single Responsibility Principle and also confuses the person who takes a look at the html first. So, when I see [ngStyle]="setStyle()", I would think there is something wrong with this code, because in general setters do not return anything.

            2. You call a method from html which will result in unpredicted behaviour like the one you are having right now. It is because, Angular has this concept called Change Detection If you haven't heard of it, you should read about it. In short, whenever an event (user click, xhr request etc.) is triggered, Angular goes through your html and your component to detect if something has changed. While doing so, if there is a method within your html, angular will call it to get the result value to do some checks which may be OK for some cases if the called method does not do anything super complicated and finishes very quickly. However, with your case, it does something, it changes the color.


            So, what can we do?



            We need to seperate the logic of setting colors and getting colors into two different methods. Also, if possible, we should avoid calling methods from html.



            I think what you are trying to do is to assign different colors to each element of the array based on previous element's color. So you can do something like following



            @Component({
            selector: 'demo',
            template: `
            <div [ngStyle]="element.style" *ngFor="let element of array1"></div>
            `
            })
            export class DemoComponent implements OnInit {

            array1 = ;

            color = 'white';

            constructor() { }

            ngOnInit() {
            // get array from somewhere
            // this.array1 =

            this.array1.forEach(element => {
            const colorConfig = this.getNextColor();
            element.style = {
            'background-color': colorConfig.color,
            'height': '382px',
            'color': colorConfig.fontColor
            };
            });
            }

            getNextColor() {
            let fontColor;
            if (this.color === 'blue') {
            this.color = 'red';
            fontColor = 'white';
            } else if (this.color === 'red') {
            this.color = 'white';
            fontColor = 'black';
            } else if (this.color === 'white') {
            this.color = 'blue';
            fontColor = 'white';
            }

            return {
            color: this.color,
            fontColor: fontColor
            };
            }

            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 10:57

























            answered Nov 15 '18 at 11:38









            Bunyamin CoskunerBunyamin Coskuner

            3,8321934




            3,8321934

























                0














                Yes, it will call multiple times since you have used *ngFor and it will create multiple div element and multiple div will call ngStyle multiple times.



                If you wan to call it once then you can wrap it like



                <div  [ngStyle]="setStyle()">
                <ng-container *ngFor="let element of array1">
                ....
                </ng-container>
                </div>


                If you want to apply the ngStyle in the same div and want to repeat the same then you should put this setStyle into some variable in use it as -



                public style;

                ngOnInit(){
                this.style = this.setStyle(); //return the styles
                }


                <div [ngStyle]="style" *ngFor="let element of array1">





                share|improve this answer




























                  0














                  Yes, it will call multiple times since you have used *ngFor and it will create multiple div element and multiple div will call ngStyle multiple times.



                  If you wan to call it once then you can wrap it like



                  <div  [ngStyle]="setStyle()">
                  <ng-container *ngFor="let element of array1">
                  ....
                  </ng-container>
                  </div>


                  If you want to apply the ngStyle in the same div and want to repeat the same then you should put this setStyle into some variable in use it as -



                  public style;

                  ngOnInit(){
                  this.style = this.setStyle(); //return the styles
                  }


                  <div [ngStyle]="style" *ngFor="let element of array1">





                  share|improve this answer


























                    0












                    0








                    0







                    Yes, it will call multiple times since you have used *ngFor and it will create multiple div element and multiple div will call ngStyle multiple times.



                    If you wan to call it once then you can wrap it like



                    <div  [ngStyle]="setStyle()">
                    <ng-container *ngFor="let element of array1">
                    ....
                    </ng-container>
                    </div>


                    If you want to apply the ngStyle in the same div and want to repeat the same then you should put this setStyle into some variable in use it as -



                    public style;

                    ngOnInit(){
                    this.style = this.setStyle(); //return the styles
                    }


                    <div [ngStyle]="style" *ngFor="let element of array1">





                    share|improve this answer













                    Yes, it will call multiple times since you have used *ngFor and it will create multiple div element and multiple div will call ngStyle multiple times.



                    If you wan to call it once then you can wrap it like



                    <div  [ngStyle]="setStyle()">
                    <ng-container *ngFor="let element of array1">
                    ....
                    </ng-container>
                    </div>


                    If you want to apply the ngStyle in the same div and want to repeat the same then you should put this setStyle into some variable in use it as -



                    public style;

                    ngOnInit(){
                    this.style = this.setStyle(); //return the styles
                    }


                    <div [ngStyle]="style" *ngFor="let element of array1">






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 15 '18 at 8:03









                    Sunil SinghSunil Singh

                    6,3672627




                    6,3672627























                        0














                        It 's better in your case to use ngClass instead of ngStyle and I don't think you need to use function at all.



                        style



                        .blue {
                        color:blue;
                        background-color:red; // many css property
                        }

                        .red {
                        color:red;
                        ...
                        }

                        .white {
                        color:white
                        ...
                        }


                        template



                        <div  [ngClass]="color" *ngFor="let element of array1" >


                        the class can have another property but if you still only changeing just the color you can use ngStyle



                        <div  [ngStyle]="{color:color}" *ngFor="let element of array1" >


                        stackblitz demo






                        share|improve this answer






























                          0














                          It 's better in your case to use ngClass instead of ngStyle and I don't think you need to use function at all.



                          style



                          .blue {
                          color:blue;
                          background-color:red; // many css property
                          }

                          .red {
                          color:red;
                          ...
                          }

                          .white {
                          color:white
                          ...
                          }


                          template



                          <div  [ngClass]="color" *ngFor="let element of array1" >


                          the class can have another property but if you still only changeing just the color you can use ngStyle



                          <div  [ngStyle]="{color:color}" *ngFor="let element of array1" >


                          stackblitz demo






                          share|improve this answer




























                            0












                            0








                            0







                            It 's better in your case to use ngClass instead of ngStyle and I don't think you need to use function at all.



                            style



                            .blue {
                            color:blue;
                            background-color:red; // many css property
                            }

                            .red {
                            color:red;
                            ...
                            }

                            .white {
                            color:white
                            ...
                            }


                            template



                            <div  [ngClass]="color" *ngFor="let element of array1" >


                            the class can have another property but if you still only changeing just the color you can use ngStyle



                            <div  [ngStyle]="{color:color}" *ngFor="let element of array1" >


                            stackblitz demo






                            share|improve this answer















                            It 's better in your case to use ngClass instead of ngStyle and I don't think you need to use function at all.



                            style



                            .blue {
                            color:blue;
                            background-color:red; // many css property
                            }

                            .red {
                            color:red;
                            ...
                            }

                            .white {
                            color:white
                            ...
                            }


                            template



                            <div  [ngClass]="color" *ngFor="let element of array1" >


                            the class can have another property but if you still only changeing just the color you can use ngStyle



                            <div  [ngStyle]="{color:color}" *ngFor="let element of array1" >


                            stackblitz demo







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 15 '18 at 8:53

























                            answered Nov 15 '18 at 7:52









                            malbarmawimalbarmawi

                            5,51331232




                            5,51331232






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53314500%2fhow-many-time-ngstyle-is-applied%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Bressuire

                                Vorschmack

                                Quarantine