Angular Universal: '.setElementClass' failing when being called with 'undefined' as className
See original GitHub issueThe two icon directives mz-icon
and mz-icon-mdi
both call the .setElementClass
function of the Renderer
with a className
value of undefined
. This will not cause any issues in the browser as raising an error would be against the spec, but due to Angular Universal pre-rendering HTML on the server using the domino package, it causes things to break.
Current Behavior
Attempting to pre-render an Angular app on the server throws an error when trying to add / remove a class that is undefined
, despite this being within the spec. This is most likely due to Angular using the domino package to create the DOM in NodeJS that doesn’t allow the input of undefined
as className while adding / removing a CSS class to an element:
Error handler that throws the error (Source)
function handleErrors(token) {
if (token === "" || token === undefined) {
utils.SyntaxError();
}
...
}
There are a three places where this is causing issues:
- MzIconDirective.handleAlign (
this.align
is initiallyundefined
) - MzIconDirective.handleSize (
this.size
is initiallyundefined
) - MzIconMdiDirective.handleAlign (
this.align
is initiallyundefined
)
Possible Solution
Current:
handleAlign(previousValue?: string) {
if (previousValue) {
this.renderer.setElementClass(this.elementRef.nativeElement, previousValue, false);
}
this.renderer.setElementClass(this.elementRef.nativeElement, this.align, !!this.align);
}
Wrap the method inside of an if
statement to make sure we are not adding / removing a class that is undefined
:
handleAlign(previousValue?: string) {
if (previousValue) {
this.renderer.setElementClass(this.elementRef.nativeElement, previousValue, false);
}
if (this.align) {
this.renderer.setElementClass(this.elementRef.nativeElement, this.align, true);
}
}
I know this is not really a bug in the ng2-materialize library, but seeing that this is such an easy fix and probably not intended in the first place, I would love to create a PR for this.
Steps to Reproduce (for bugs)
Sadly I cannot provide a fiddle to reproduce this as this only affects Angular Universal, where the app is being rendered by the server and not the browser, and I wasn’t able to set one up for that. I’m using the pre-render strategy mentioned in the Angular universal starter kit, running Angular 6.0.0.
Your Environment
- Version used: 1.8.1
- Angular version used: 6.0.0
- Browser Name and version: Server side (NodeJS v8.9.1)
Issue Analytics
- State:
- Created 5 years ago
- Comments:12 (12 by maintainers)
Top GitHub Comments
Thanks for giving me the opportunity to help out!
There is a lot of tests to correct if replacing for
Renderer2
. We were planing to remove it when migrating to Materialize-Css v1.0 since we will have to touch pretty much everything to remove JQuery and use plain JavaScript instead.