Search code examples
angularprettier

ESLint + Prettier adds parentheses wrong on Angular pipe


So, we have an Angular project running on version 8.2.14, and we recently introduced Prettier and ESLint as an autoformatter to keep everything to a standard.

However, Prettier formats the parentheses on our HTML file and wrongly places parentheses on ternary operators that also use Angular Pipes.

What I want to know is a rule that does not mess this (Angular pipes) up, or if we can disable parentheses rules only for HTML files, but keep other rules working.

The original code (works normally, and is expected):

<!-- code -->
<td data-label="small text">
  {{ booleanValue ? 'Yes' : 'No' | ourCustomPipe }}
</td>

Code after being formatted and saved (part of the team uses autoformat on save, so it's important to change the rule):

<!-- code -->
<td data-label="small text">
  {{ booleanValue ? 'Yes' : ('No' | ourCustomPipe) }}
</td>

Another expected outcome besides the original:

<!-- code -->
<td data-label="small text">
  {{ (booleanValue ? 'Yes' : 'No') | ourCustomPipe }}
</td>

Thank you for your attention.


Solution

  • Are you sure that your code works correctly? I think that your Prettier is fine. Look at this code:

    @Pipe({
      name: 'ourCustomPipe',
      standalone: true,
    })
    class OurCustomPipe implements PipeTransform {
      transform(value: string): string {
        return `${value === 'Yes' ? '👍🏻' : '👎🏻'} ${value}`;
      }
    }
    
    @Component({
      selector: 'my-app',
      standalone: true,
      imports: [CommonModule, OurCustomPipe],
      template: `
        <pre>
          a: {{ true ? 'Yes' : 'No' | ourCustomPipe }}
          b: {{ false ? 'Yes' : 'No' | ourCustomPipe }}
          c: {{ (true ? 'Yes' : 'No') | ourCustomPipe }}
          d: {{ (false ? 'Yes' : 'No') | ourCustomPipe }}
        </pre>
      `,
    })
    export class App {}
    

    and the output from this is:

          a: Yes
          b: 👎🏻 No
          c: 👍🏻 Yes
          d: 👎🏻 No
    

    As you can see, there is no 👍🏻 emoji in the first case. You should wrap the entire condition in parentheses, as shown in the last example. Otherwise, pipe only affects values directly before „|” character.