Skip to content

Commit

Permalink
fix(NgClass): throw a descriptive error when CSS class is not a string (
Browse files Browse the repository at this point in the history
  • Loading branch information
pkozlowski-opensource authored and vikerman committed Nov 7, 2016
1 parent 22c021c commit f3793b5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
12 changes: 9 additions & 3 deletions modules/@angular/common/src/directives/ng_class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import {CollectionChangeRecord, Directive, DoCheck, ElementRef, Input, IterableDiffer, IterableDiffers, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core';

import {isListLikeIterable} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {isPresent, stringify} from '../facade/lang';

/**
* @ngModule CommonModule
Expand Down Expand Up @@ -108,8 +108,14 @@ export class NgClass implements DoCheck {
}

private _applyIterableChanges(changes: any): void {
changes.forEachAddedItem(
(record: CollectionChangeRecord) => this._toggleClass(record.item, true));
changes.forEachAddedItem((record: CollectionChangeRecord) => {
if (typeof record.item === 'string') {
this._toggleClass(record.item, true);
} else {
throw new Error(
`NgClass can only toggle CSS classes expressed as strings, got ${stringify(record.item)}`);
}
});

changes.forEachRemovedItem(
(record: CollectionChangeRecord) => this._toggleClass(record.item, false));
Expand Down
10 changes: 8 additions & 2 deletions modules/@angular/common/test/directives/ng_class_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import {Component} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';

export function main() {
describe('binding to CSS class list', () => {
Expand Down Expand Up @@ -187,6 +186,13 @@ export function main() {
getComponent().arrExpr = ['foo bar baz foobar'];
detectChangesAndExpectClassName('foo bar baz foobar');
}));

it('should throw with descriptive error message when CSS class is not a string', () => {
fixture = createTestComponent(`<div [ngClass]="['foo', {}]"></div>`);
expect(() => fixture.detectChanges())
.toThrowError(
/NgClass can only toggle CSS classes expressed as strings, got \[object Object\]/);
});
});

describe('expressions evaluating to sets', () => {
Expand Down Expand Up @@ -348,4 +354,4 @@ class TestComponent {
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent);
}
}

0 comments on commit f3793b5

Please sign in to comment.