angularprettierprettier-vscode

Problem when formatting Angular inline template on VSCode


I always have weird and non working formating when using inline template. Like this line:

template: `<div class="filter"><input type="checkbox" id="switch" /><label for="switch">Toggle</label></div>`,

Is formatted to:

template: `<di class="filter"><input type="checkbox" id="switch" /><label for="switch">Toggle</label></di>
>`,

I use format on save with prettier. Here is my .prettierrc.json:

{
  "trailingComma": "es5",
  "tabWidth": 2,
  "singleQuote": true,
  "useTabs": false,
  "printWidth": 120,
  "overrides": [
    {
      "files": "*.scss",
      "options": {
        "singleQuote": false
      }
    },
    {
      "files": "*.html",
      "options": {
        "parser": "html",
        "singleQuote": false
      }
    },
    {
      "files": "*.component.html",
      "options": {
        "parser": "angular"
      }
    }
  ]
}

Here is my tsconfig.json:

 {
  "noImplicitAny": true,
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2020",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "noImplicitAny": true,
    "target": "es2020",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2020", "dom"],
    "baseUrl": "./",
    "paths": {
      "@app/*": ["src/app/*"],
      "@core": ["src/app/@core"],
      "@core/*": ["src/app/@core/*"],
      "@shared": ["src/app/@shared"],
      "@shared/*": ["src/app/@shared/*"],
      "@modules/*": ["src/app/modulesV2/*"],
      "@env/*": ["src/environments/*"]
    },
    "skipLibCheck": true
  },
  "angularCompilerOptions": {
    "strictTemplates": true,
    "strictInjectionParameters": true,
    "preserveWhitespaces": true
  }
}

Edit: Made it work thanks to @inkredusk adding this to the overrides property in my .prettierrc.json:

{
  "files": "*.component.ts",
  "options": {
    "htmlWhitespaceSensitivity": "ignore"
  }
}

Solution

  • Can you please try setting the option --html-whitespace-sensitivity to ignore and hopefully it should work.

    As per the docs, Whitespace-sensitive formatting wraps the tags in such a way as to avoid adding or removing significant whitespace.

    Reference link: Whitespace sensitive formatting