Workaround for ‘Template parse errors’ in Angular

This was one of the more frustrating issues with Angular 2/4/+. It’s not an issue with Angular 2/4/+ per se, but with how webpack bundles the supporting HTML files.

This issue happens when you run webpack with the production flag (webpack -p). The compilation completes, but running the site generates a runtime error: Template parse errors

Uncaught Error: Template parse errors:
Unexpected closing tag "a". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("<i class="fa fa-home"></i> Home</a></li> <li class=nav-item><a class=nav-link href=/ams/#/search>AMS[ERROR ->]</a></li> <li class=nav-item><a class=nav-link href=/ams/#/logout><i class="fa fa-adn"></i> Logout</a"): ng:///e/e.html@0:557 Unexpected closing tag "a". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("MS</a></li> <li class=nav-item><a class=nav-link href=/ams/#/logout><i class="fa fa-adn"></i> Logout[ERROR ->]</a></li></ul></div></div></div></header>

The suspected HTML:


<div class="navbar navbar-light bg-faded rounded navbar-toggleable-md">
    <div class="collapse navbar-collapse" id="containernavbar">
        <global-search></global-search>
        <ul class="navbar-nav">
            <li class="nav-item active"><a class="nav-link" routerLink="['']"><i class="fa fa-home"></i> Home</a></li>
            <li class="nav-item"><a class="nav-link" href="/ams/#/search">AMS</a></li>
            <li class="nav-item"><a class="nav-link" href="/ams/#/logout"><i class="fa fa-adn"></i> Logout</a></li>
        </ul>
    </div>
</div>

I couldn’t find anything wrong with this HTML. I ran it through multiple online HTML validators, and the HTML always came back as valid HTML. After a few weeks of beating my head against the wall and getting nowhere, I figured there must be a way around this issue.

What I discovered, via a GitHub thread (sorry I lost the link to it) was it’s the HTML loader trying to minimize the HTML that’s causing the problem. If the HTML minimization is turned off, this issue goes away. To be fair, most folks with this error had invalid HTML. I encourage you to check your HTML before working around this issue, you may be just pushing the issue down the road.

Turning off HTML minimization is easy as updating your HTML-loader in the webpack.config.js.

Before:

{
  test: /.html$/,
  loader: 'html-loader'
},

After:

{
    test: /.html$/,
    use: [{
        loader: 'html-loader',
        options: {
            minimize: false,
            removeComments: false,
            collapseWhitespace: false,
            removeAttributeQuotes: false,
        }
    }],
},

Leave A Comment

Your email address will not be published. Required fields are marked *