htmlangulartypescriptng-style

Can Angular ngStyle take more than one function? What's the workaround if not?


With ngStyle, are you able to add multiple conditions to multiple attributes?

I need to change my text color and background color based on a certain JSON value.

Background Info:

I am working to make a tab bar similar to a browser. In each tab there is a header/title and subheader. The Subheader's style changes based on the tab/array data. Here is what the tab-bar design looks like: enter image description here

I'm focusing on the Subheader style, the Planning and FPE ones.

Here is what my tab array looks like:

 tabs = [
    {
      flightName: "Flight 1",
      stagePhase: "PRE-FPE",
      control: "View Only"
    },
    {
      flightName: "Flight 2",
      stagePhase: "PLANNING",
      control: "Plan and Load"
    },
    {
      flightName: "Flight 3",
      stagePhase: "PLANNING",
      control: "Closeout"
    },
    {
      flightName: "Flight 4",
      stagePhase: "FPE",
      control: "View Only"
    }
  ];

If the tabs.tab.control attribute is "View Only" then the background-color will be transparent, "Plan and Load" : light grey, and "Closeout" : white and then also change the text-color to dark.

So for the background color alone ngStyle function can look like: (Typescript)

getBgColor(control) {
  switch (control) {
    case 'View Only':
      return '#ffcccc00';
    case 'Editing':
      return '#cce6ff44';
    case 'Closeout':
      return 'white';
  }
}

Here's the HTML: (focus on the ngStyle)

<ul class="tabs" id="tabsList" *ngFor="let tab of tabs">
    
    <li>
      <a href="javascript:void(0)" class="flight-title"> {{ tab.flightName }} </a>
      <a [ngStyle]="{'background': getBackColor(tab.control) }" class="stage"> {{ tab.stagePhase }}
      </a>
      <em (click)="closeTab(tabs.indexOf(tab))" class="close-icon"> </em>
    </li>
</ul>

Problem:

Now for the second <a> tag, I'd like to have 2 functions called: getBgColor() and getTxtColor(). But simply adding another function doesn't work:

<a [ngStyle]="{'background': getBgColor(tab.control)}, {'color': getTxtColor(tab.control) }" class="stage"> {{ tab.stagePhase }}
      </a>

With the extra function:

getTxtColor(control) {
    switch (control) {
      case 'View Only':
        return 'white';
      case 'Plan and Load':
        return 'white';
      case 'Closeout':
        return 'black';
    }
  }

I can't do both of these functions and they need to be returned, what are my options?


Solution

  • NgStyle does allow the use of multiple functions. But they need to be within only one set of brackets.

    Try with only one bracket pair {}:

    [ngStyle]="{'background': getBgColor(tab.control), 'color': getTxtColor(tab.control) }"