refactor(NgClass): cleanup, readability (#11467)

This commit is contained in:
Victor Berchet 2016-09-09 12:03:51 -07:00 committed by Evan Martin
parent 673de004d2
commit f5d44a42c9
4 changed files with 208 additions and 257 deletions

View File

@ -8,10 +8,8 @@
import {CollectionChangeRecord, Directive, DoCheck, ElementRef, Input, IterableDiffer, IterableDiffers, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core'; import {CollectionChangeRecord, Directive, DoCheck, ElementRef, Input, IterableDiffer, IterableDiffers, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core';
import {StringMapWrapper, isListLikeIterable} from '../facade/collection'; import {isListLikeIterable} from '../facade/collection';
import {isArray, isPresent, isString} from '../facade/lang'; import {isPresent} from '../facade/lang';
/** /**
* The `NgClass` directive conditionally adds and removes CSS classes on an HTML element based on * The `NgClass` directive conditionally adds and removes CSS classes on an HTML element based on
@ -79,7 +77,7 @@ export class NgClass implements DoCheck {
private _iterableDiffer: IterableDiffer; private _iterableDiffer: IterableDiffer;
private _keyValueDiffer: KeyValueDiffer; private _keyValueDiffer: KeyValueDiffer;
private _initialClasses: string[] = []; private _initialClasses: string[] = [];
private _rawClass: string[]|Set<string>; private _rawClass: string[]|Set<string>|{[klass: string]: any};
constructor( constructor(
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers, private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
@ -87,58 +85,57 @@ export class NgClass implements DoCheck {
@Input('class') @Input('class')
set initialClasses(v: string) { set klass(v: string) {
this._applyInitialClasses(true); this._applyInitialClasses(true);
this._initialClasses = isPresent(v) && isString(v) ? v.split(' ') : []; this._initialClasses = typeof v === 'string' ? v.split(/\s+/) : [];
this._applyInitialClasses(false); this._applyInitialClasses(false);
this._applyClasses(this._rawClass, false); this._applyClasses(this._rawClass, false);
} }
@Input() @Input()
set ngClass(v: string|string[]|Set<string>|{[key: string]: any}) { set ngClass(v: string|string[]|Set<string>|{[klass: string]: any}) {
this._cleanupClasses(this._rawClass); this._cleanupClasses(this._rawClass);
if (isString(v)) {
v = (<string>v).split(' ');
}
this._rawClass = <string[]|Set<string>>v;
this._iterableDiffer = null; this._iterableDiffer = null;
this._keyValueDiffer = null; this._keyValueDiffer = null;
if (isPresent(v)) {
if (isListLikeIterable(v)) { this._rawClass = typeof v === 'string' ? v.split(/\s+/) : v;
this._iterableDiffer = this._iterableDiffers.find(v).create(null);
if (this._rawClass) {
if (isListLikeIterable(this._rawClass)) {
this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create(null);
} else { } else {
this._keyValueDiffer = this._keyValueDiffers.find(v).create(null); this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create(null);
} }
} }
} }
ngDoCheck(): void { ngDoCheck(): void {
if (isPresent(this._iterableDiffer)) { if (this._iterableDiffer) {
var changes = this._iterableDiffer.diff(this._rawClass); const changes = this._iterableDiffer.diff(this._rawClass);
if (isPresent(changes)) { if (changes) {
this._applyIterableChanges(changes); this._applyIterableChanges(changes);
} }
} } else if (this._keyValueDiffer) {
if (isPresent(this._keyValueDiffer)) { const changes = this._keyValueDiffer.diff(this._rawClass);
var changes = this._keyValueDiffer.diff(this._rawClass); if (changes) {
if (isPresent(changes)) {
this._applyKeyValueChanges(changes); this._applyKeyValueChanges(changes);
} }
} }
} }
private _cleanupClasses(rawClassVal: string[]|Set<string>|{[key: string]: any}): void { private _cleanupClasses(rawClassVal: string[]|Set<string>|{[klass: string]: any}): void {
this._applyClasses(rawClassVal, true); this._applyClasses(rawClassVal, true);
this._applyInitialClasses(false); this._applyInitialClasses(false);
} }
private _applyKeyValueChanges(changes: any): void { private _applyKeyValueChanges(changes: any): void {
changes.forEachAddedItem( changes.forEachAddedItem(
(record: KeyValueChangeRecord) => { this._toggleClass(record.key, record.currentValue); }); (record: KeyValueChangeRecord) => this._toggleClass(record.key, record.currentValue));
changes.forEachChangedItem( changes.forEachChangedItem(
(record: KeyValueChangeRecord) => { this._toggleClass(record.key, record.currentValue); }); (record: KeyValueChangeRecord) => this._toggleClass(record.key, record.currentValue));
changes.forEachRemovedItem((record: KeyValueChangeRecord) => { changes.forEachRemovedItem((record: KeyValueChangeRecord) => {
if (record.previousValue) { if (record.previousValue) {
this._toggleClass(record.key, false); this._toggleClass(record.key, false);
@ -148,42 +145,34 @@ export class NgClass implements DoCheck {
private _applyIterableChanges(changes: any): void { private _applyIterableChanges(changes: any): void {
changes.forEachAddedItem( changes.forEachAddedItem(
(record: CollectionChangeRecord) => { this._toggleClass(record.item, true); }); (record: CollectionChangeRecord) => this._toggleClass(record.item, true));
changes.forEachRemovedItem( changes.forEachRemovedItem(
(record: CollectionChangeRecord) => { this._toggleClass(record.item, false); }); (record: CollectionChangeRecord) => this._toggleClass(record.item, false));
} }
private _applyInitialClasses(isCleanup: boolean) { private _applyInitialClasses(isCleanup: boolean) {
this._initialClasses.forEach(className => this._toggleClass(className, !isCleanup)); this._initialClasses.forEach(klass => this._toggleClass(klass, !isCleanup));
} }
private _applyClasses( private _applyClasses(
rawClassVal: string[]|Set<string>|{[key: string]: any}, isCleanup: boolean) { rawClassVal: string[]|Set<string>|{[key: string]: any}, isCleanup: boolean) {
if (isPresent(rawClassVal)) { if (rawClassVal) {
if (isArray(rawClassVal)) { if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) {
(<string[]>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup)); (<any>rawClassVal).forEach((klass: string) => this._toggleClass(klass, !isCleanup));
} else if (rawClassVal instanceof Set) {
(<Set<string>>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup));
} else { } else {
StringMapWrapper.forEach( Object.keys(rawClassVal).forEach(klass => {
<{[k: string]: any}>rawClassVal, (expVal: any, className: string) => { if (isPresent(rawClassVal[klass])) this._toggleClass(klass, !isCleanup);
if (isPresent(expVal)) this._toggleClass(className, !isCleanup);
}); });
} }
} }
} }
private _toggleClass(className: string, enabled: boolean): void { private _toggleClass(klass: string, enabled: boolean): void {
className = className.trim(); klass = klass.trim();
if (className.length > 0) { if (klass) {
if (className.indexOf(' ') > -1) { klass.split(/\s+/g).forEach(
var classes = className.split(/\s+/g); klass => { this._renderer.setElementClass(this._ngEl.nativeElement, klass, enabled); });
for (var i = 0, len = classes.length; i < len; i++) {
this._renderer.setElementClass(this._ngEl.nativeElement, classes[i], enabled);
}
} else {
this._renderer.setElementClass(this._ngEl.nativeElement, className, enabled);
}
} }
} }
} }

View File

@ -6,20 +6,23 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {NgClass, NgFor} from '@angular/common';
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing'; import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {ListWrapper, StringMapWrapper} from '../../src/facade/collection';
function detectChangesAndCheck(fixture: ComponentFixture<any>, classes: string) {
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.className).toEqual(classes);
}
export function main() { export function main() {
describe('binding to CSS class list', () => { describe('binding to CSS class list', () => {
let fixture: ComponentFixture<any>;
function detectChangesAndExpectClassName(classes: string): void {
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.className).toEqual(classes);
}
function getComponent(): TestComponent { return fixture.debugElement.componentInstance; }
afterEach(() => { fixture = null; });
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [TestComponent], declarations: [TestComponent],
@ -27,268 +30,221 @@ export function main() {
}); });
it('should clean up when the directive is destroyed', async(() => { it('should clean up when the directive is destroyed', async(() => {
let template = '<div *ngFor="let item of items" [ngClass]="item"></div>'; fixture = createTestComponent('<div *ngFor="let item of items" [ngClass]="item"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
fixture.debugElement.componentInstance.items = [['0']]; getComponent().items = [['0']];
fixture.detectChanges(); fixture.detectChanges();
fixture.debugElement.componentInstance.items = [['1']]; getComponent().items = [['1']];
detectChangesAndExpectClassName('1');
detectChangesAndCheck(fixture, '1');
})); }));
describe('expressions evaluating to objects', () => { describe('expressions evaluating to objects', () => {
it('should add classes specified in an object literal', async(() => { it('should add classes specified in an object literal', async(() => {
let template = '<div [ngClass]="{foo: true, bar: false}"></div>'; fixture = createTestComponent('<div [ngClass]="{foo: true, bar: false}"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo'); detectChangesAndExpectClassName('foo');
})); }));
it('should add classes specified in an object literal without change in class names', it('should add classes specified in an object literal without change in class names',
async(() => { async(() => {
let template = `<div [ngClass]="{'foo-bar': true, 'fooBar': true}"></div>`; fixture =
TestBed.overrideComponent(TestComponent, {set: {template: template}}); createTestComponent(`<div [ngClass]="{'foo-bar': true, 'fooBar': true}"></div>`);
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo-bar fooBar'); detectChangesAndExpectClassName('foo-bar fooBar');
})); }));
it('should add and remove classes based on changes in object literal values', async(() => { it('should add and remove classes based on changes in object literal values', async(() => {
let template = '<div [ngClass]="{foo: condition, bar: !condition}"></div>'; fixture =
TestBed.overrideComponent(TestComponent, {set: {template: template}}); createTestComponent('<div [ngClass]="{foo: condition, bar: !condition}"></div>');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo'); detectChangesAndExpectClassName('foo');
fixture.debugElement.componentInstance.condition = false; getComponent().condition = false;
detectChangesAndCheck(fixture, 'bar'); detectChangesAndExpectClassName('bar');
})); }));
it('should add and remove classes based on changes to the expression object', async(() => { it('should add and remove classes based on changes to the expression object', async(() => {
let template = '<div [ngClass]="objExpr"></div>'; fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); let objExpr = getComponent().objExpr;
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo'); detectChangesAndExpectClassName('foo');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true); objExpr['bar'] = true;
detectChangesAndCheck(fixture, 'foo bar'); detectChangesAndExpectClassName('foo bar');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'baz', true); objExpr['baz'] = true;
detectChangesAndCheck(fixture, 'foo bar baz'); detectChangesAndExpectClassName('foo bar baz');
StringMapWrapper.delete(fixture.debugElement.componentInstance.objExpr, 'bar'); delete (objExpr['bar']);
detectChangesAndCheck(fixture, 'foo baz'); detectChangesAndExpectClassName('foo baz');
})); }));
it('should add and remove classes based on reference changes to the expression object', it('should add and remove classes based on reference changes to the expression object',
async(() => { async(() => {
let template = '<div [ngClass]="objExpr"></div>'; fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo'); detectChangesAndExpectClassName('foo');
fixture.debugElement.componentInstance.objExpr = {foo: true, bar: true}; getComponent().objExpr = {foo: true, bar: true};
detectChangesAndCheck(fixture, 'foo bar'); detectChangesAndExpectClassName('foo bar');
fixture.debugElement.componentInstance.objExpr = {baz: true}; getComponent().objExpr = {baz: true};
detectChangesAndCheck(fixture, 'baz'); detectChangesAndExpectClassName('baz');
})); }));
it('should remove active classes when expression evaluates to null', async(() => { it('should remove active classes when expression evaluates to null', async(() => {
let template = '<div [ngClass]="objExpr"></div>'; fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo'); detectChangesAndExpectClassName('foo');
fixture.debugElement.componentInstance.objExpr = null; getComponent().objExpr = null;
detectChangesAndCheck(fixture, ''); detectChangesAndExpectClassName('');
fixture.debugElement.componentInstance.objExpr = {'foo': false, 'bar': true}; getComponent().objExpr = {'foo': false, 'bar': true};
detectChangesAndCheck(fixture, 'bar'); detectChangesAndExpectClassName('bar');
})); }));
it('should allow multiple classes per expression', async(() => { it('should allow multiple classes per expression', async(() => {
let template = '<div [ngClass]="objExpr"></div>'; fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
fixture.debugElement.componentInstance.objExpr = {'bar baz': true, 'bar1 baz1': true}; getComponent().objExpr = {'bar baz': true, 'bar1 baz1': true};
detectChangesAndCheck(fixture, 'bar baz bar1 baz1'); detectChangesAndExpectClassName('bar baz bar1 baz1');
fixture.debugElement.componentInstance.objExpr = {'bar baz': false, 'bar1 baz1': true}; getComponent().objExpr = {'bar baz': false, 'bar1 baz1': true};
detectChangesAndCheck(fixture, 'bar1 baz1'); detectChangesAndExpectClassName('bar1 baz1');
})); }));
it('should split by one or more spaces between classes', async(() => { it('should split by one or more spaces between classes', async(() => {
let template = '<div [ngClass]="objExpr"></div>'; fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
fixture.debugElement.componentInstance.objExpr = {'foo bar baz': true}; getComponent().objExpr = {'foo bar baz': true};
detectChangesAndCheck(fixture, 'foo bar baz'); detectChangesAndExpectClassName('foo bar baz');
})); }));
}); });
describe('expressions evaluating to lists', () => { describe('expressions evaluating to lists', () => {
it('should add classes specified in a list literal', async(() => { it('should add classes specified in a list literal', async(() => {
let template = `<div [ngClass]="['foo', 'bar', 'foo-bar', 'fooBar']"></div>`; fixture =
TestBed.overrideComponent(TestComponent, {set: {template: template}}); createTestComponent(`<div [ngClass]="['foo', 'bar', 'foo-bar', 'fooBar']"></div>`);
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo bar foo-bar fooBar'); detectChangesAndExpectClassName('foo bar foo-bar fooBar');
})); }));
it('should add and remove classes based on changes to the expression', async(() => { it('should add and remove classes based on changes to the expression', async(() => {
let template = '<div [ngClass]="arrExpr"></div>'; fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); let arrExpr = getComponent().arrExpr;
let fixture = TestBed.createComponent(TestComponent); detectChangesAndExpectClassName('foo');
var arrExpr: string[] = fixture.debugElement.componentInstance.arrExpr;
detectChangesAndCheck(fixture, 'foo');
arrExpr.push('bar'); arrExpr.push('bar');
detectChangesAndCheck(fixture, 'foo bar'); detectChangesAndExpectClassName('foo bar');
arrExpr[1] = 'baz'; arrExpr[1] = 'baz';
detectChangesAndCheck(fixture, 'foo baz'); detectChangesAndExpectClassName('foo baz');
ListWrapper.remove(fixture.debugElement.componentInstance.arrExpr, 'baz'); getComponent().arrExpr = arrExpr.filter((v: string) => v !== 'baz');
detectChangesAndCheck(fixture, 'foo'); detectChangesAndExpectClassName('foo');
})); }));
it('should add and remove classes when a reference changes', async(() => { it('should add and remove classes when a reference changes', async(() => {
let template = '<div [ngClass]="arrExpr"></div>'; fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); detectChangesAndExpectClassName('foo');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo');
fixture.debugElement.componentInstance.arrExpr = ['bar']; getComponent().arrExpr = ['bar'];
detectChangesAndCheck(fixture, 'bar'); detectChangesAndExpectClassName('bar');
})); }));
it('should take initial classes into account when a reference changes', async(() => { it('should take initial classes into account when a reference changes', async(() => {
let template = '<div class="foo" [ngClass]="arrExpr"></div>'; fixture = createTestComponent('<div class="foo" [ngClass]="arrExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); detectChangesAndExpectClassName('foo');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo');
fixture.debugElement.componentInstance.arrExpr = ['bar']; getComponent().arrExpr = ['bar'];
detectChangesAndCheck(fixture, 'foo bar'); detectChangesAndExpectClassName('foo bar');
})); }));
it('should ignore empty or blank class names', async(() => { it('should ignore empty or blank class names', async(() => {
let template = '<div class="foo" [ngClass]="arrExpr"></div>'; fixture = createTestComponent('<div class="foo" [ngClass]="arrExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); getComponent().arrExpr = ['', ' '];
let fixture = TestBed.createComponent(TestComponent); detectChangesAndExpectClassName('foo');
fixture.debugElement.componentInstance.arrExpr = ['', ' '];
detectChangesAndCheck(fixture, 'foo');
})); }));
it('should trim blanks from class names', async(() => { it('should trim blanks from class names', async(() => {
var template = '<div class="foo" [ngClass]="arrExpr"></div>'; fixture = createTestComponent('<div class="foo" [ngClass]="arrExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
fixture.debugElement.componentInstance.arrExpr = [' bar ']; getComponent().arrExpr = [' bar '];
detectChangesAndCheck(fixture, 'foo bar'); detectChangesAndExpectClassName('foo bar');
})); }));
it('should allow multiple classes per item in arrays', async(() => { it('should allow multiple classes per item in arrays', async(() => {
var template = '<div [ngClass]="arrExpr"></div>'; fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
fixture.debugElement.componentInstance.arrExpr = ['foo bar baz', 'foo1 bar1 baz1']; getComponent().arrExpr = ['foo bar baz', 'foo1 bar1 baz1'];
detectChangesAndCheck(fixture, 'foo bar baz foo1 bar1 baz1'); detectChangesAndExpectClassName('foo bar baz foo1 bar1 baz1');
fixture.debugElement.componentInstance.arrExpr = ['foo bar baz foobar']; getComponent().arrExpr = ['foo bar baz foobar'];
detectChangesAndCheck(fixture, 'foo bar baz foobar'); detectChangesAndExpectClassName('foo bar baz foobar');
})); }));
}); });
describe('expressions evaluating to sets', () => { describe('expressions evaluating to sets', () => {
it('should add and remove classes if the set instance changed', async(() => { it('should add and remove classes if the set instance changed', async(() => {
var template = '<div [ngClass]="setExpr"></div>'; fixture = createTestComponent('<div [ngClass]="setExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); let setExpr = new Set<string>();
let fixture = TestBed.createComponent(TestComponent);
var setExpr = new Set<string>();
setExpr.add('bar'); setExpr.add('bar');
fixture.debugElement.componentInstance.setExpr = setExpr; getComponent().setExpr = setExpr;
detectChangesAndCheck(fixture, 'bar'); detectChangesAndExpectClassName('bar');
setExpr = new Set<string>(); setExpr = new Set<string>();
setExpr.add('baz'); setExpr.add('baz');
fixture.debugElement.componentInstance.setExpr = setExpr; getComponent().setExpr = setExpr;
detectChangesAndCheck(fixture, 'baz'); detectChangesAndExpectClassName('baz');
})); }));
}); });
describe('expressions evaluating to string', () => { describe('expressions evaluating to string', () => {
it('should add classes specified in a string literal', async(() => { it('should add classes specified in a string literal', async(() => {
var template = `<div [ngClass]="'foo bar foo-bar fooBar'"></div>`; fixture = createTestComponent(`<div [ngClass]="'foo bar foo-bar fooBar'"></div>`);
TestBed.overrideComponent(TestComponent, {set: {template: template}}); detectChangesAndExpectClassName('foo bar foo-bar fooBar');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo bar foo-bar fooBar');
})); }));
it('should add and remove classes based on changes to the expression', async(() => { it('should add and remove classes based on changes to the expression', async(() => {
var template = '<div [ngClass]="strExpr"></div>'; fixture = createTestComponent('<div [ngClass]="strExpr"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); detectChangesAndExpectClassName('foo');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo');
fixture.debugElement.componentInstance.strExpr = 'foo bar'; getComponent().strExpr = 'foo bar';
detectChangesAndCheck(fixture, 'foo bar'); detectChangesAndExpectClassName('foo bar');
fixture.debugElement.componentInstance.strExpr = 'baz'; getComponent().strExpr = 'baz';
detectChangesAndCheck(fixture, 'baz'); detectChangesAndExpectClassName('baz');
})); }));
it('should remove active classes when switching from string to null', async(() => { it('should remove active classes when switching from string to null', async(() => {
var template = `<div [ngClass]="strExpr"></div>`; fixture = createTestComponent(`<div [ngClass]="strExpr"></div>`);
TestBed.overrideComponent(TestComponent, {set: {template: template}}); detectChangesAndExpectClassName('foo');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo');
fixture.debugElement.componentInstance.strExpr = null;
detectChangesAndCheck(fixture, '');
getComponent().strExpr = null;
detectChangesAndExpectClassName('');
})); }));
it('should take initial classes into account when switching from string to null', it('should take initial classes into account when switching from string to null',
async(() => { async(() => {
var template = `<div class="foo" [ngClass]="strExpr"></div>`; fixture = createTestComponent(`<div class="foo" [ngClass]="strExpr"></div>`);
TestBed.overrideComponent(TestComponent, {set: {template: template}}); detectChangesAndExpectClassName('foo');
let fixture = TestBed.createComponent(TestComponent);
detectChangesAndCheck(fixture, 'foo');
fixture.debugElement.componentInstance.strExpr = null;
detectChangesAndCheck(fixture, 'foo');
getComponent().strExpr = null;
detectChangesAndExpectClassName('foo');
})); }));
it('should ignore empty and blank strings', async(() => { it('should ignore empty and blank strings', async(() => {
var template = `<div class="foo" [ngClass]="strExpr"></div>`; fixture = createTestComponent(`<div class="foo" [ngClass]="strExpr"></div>`);
TestBed.overrideComponent(TestComponent, {set: {template: template}}); getComponent().strExpr = '';
let fixture = TestBed.createComponent(TestComponent); detectChangesAndExpectClassName('foo');
fixture.debugElement.componentInstance.strExpr = '';
detectChangesAndCheck(fixture, 'foo');
})); }));
}); });
@ -296,83 +252,82 @@ export function main() {
describe('cooperation with other class-changing constructs', () => { describe('cooperation with other class-changing constructs', () => {
it('should co-operate with the class attribute', async(() => { it('should co-operate with the class attribute', async(() => {
var template = '<div [ngClass]="objExpr" class="init foo"></div>'; fixture = createTestComponent('<div [ngClass]="objExpr" class="init foo"></div>');
TestBed.overrideComponent(TestComponent, {set: {template: template}}); let objExpr = getComponent().objExpr;
let fixture = TestBed.createComponent(TestComponent);
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, 'init foo bar');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false); objExpr['bar'] = true;
detectChangesAndCheck(fixture, 'init bar'); detectChangesAndExpectClassName('init foo bar');
fixture.debugElement.componentInstance.objExpr = null; objExpr['foo'] = false;
detectChangesAndCheck(fixture, 'init foo'); detectChangesAndExpectClassName('init bar');
getComponent().objExpr = null;
detectChangesAndExpectClassName('init foo');
})); }));
it('should co-operate with the interpolated class attribute', async(() => { it('should co-operate with the interpolated class attribute', async(() => {
var template = `<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`; fixture = createTestComponent(`<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`);
TestBed.overrideComponent(TestComponent, {set: {template: template}}); let objExpr = getComponent().objExpr;
let fixture = TestBed.createComponent(TestComponent);
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, `init foo bar`);
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false); objExpr['bar'] = true;
detectChangesAndCheck(fixture, `init bar`); detectChangesAndExpectClassName(`init foo bar`);
fixture.debugElement.componentInstance.objExpr = null; objExpr['foo'] = false;
detectChangesAndCheck(fixture, `init foo`); detectChangesAndExpectClassName(`init bar`);
getComponent().objExpr = null;
detectChangesAndExpectClassName(`init foo`);
})); }));
it('should co-operate with the class attribute and binding to it', async(() => { it('should co-operate with the class attribute and binding to it', async(() => {
var template = `<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`; fixture =
TestBed.overrideComponent(TestComponent, {set: {template: template}}); createTestComponent(`<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`);
let fixture = TestBed.createComponent(TestComponent); let objExpr = getComponent().objExpr;
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, `init foo bar`);
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false); objExpr['bar'] = true;
detectChangesAndCheck(fixture, `init bar`); detectChangesAndExpectClassName(`init foo bar`);
fixture.debugElement.componentInstance.objExpr = null; objExpr['foo'] = false;
detectChangesAndCheck(fixture, `init foo`); detectChangesAndExpectClassName(`init bar`);
getComponent().objExpr = null;
detectChangesAndExpectClassName(`init foo`);
})); }));
it('should co-operate with the class attribute and class.name binding', async(() => { it('should co-operate with the class attribute and class.name binding', async(() => {
var template = const template =
'<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>'; '<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>';
TestBed.overrideComponent(TestComponent, {set: {template: template}}); fixture = createTestComponent(template);
let fixture = TestBed.createComponent(TestComponent); let objExpr = getComponent().objExpr;
detectChangesAndCheck(fixture, 'init foo baz');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true); detectChangesAndExpectClassName('init foo baz');
detectChangesAndCheck(fixture, 'init foo baz bar');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false); objExpr['bar'] = true;
detectChangesAndCheck(fixture, 'init baz bar'); detectChangesAndExpectClassName('init foo baz bar');
fixture.debugElement.componentInstance.condition = false; objExpr['foo'] = false;
detectChangesAndCheck(fixture, 'init bar'); detectChangesAndExpectClassName('init baz bar');
getComponent().condition = false;
detectChangesAndExpectClassName('init bar');
})); }));
it('should co-operate with initial class and class attribute binding when binding changes', it('should co-operate with initial class and class attribute binding when binding changes',
async(() => { async(() => {
var template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>'; const template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>';
TestBed.overrideComponent(TestComponent, {set: {template: template}}); fixture = createTestComponent(template);
let fixture = TestBed.createComponent(TestComponent); let cmp = getComponent();
detectChangesAndCheck(fixture, 'init foo');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true); detectChangesAndExpectClassName('init foo');
detectChangesAndCheck(fixture, 'init foo bar');
fixture.debugElement.componentInstance.strExpr = 'baz'; cmp.objExpr['bar'] = true;
detectChangesAndCheck(fixture, 'init bar baz foo'); detectChangesAndExpectClassName('init foo bar');
fixture.debugElement.componentInstance.objExpr = null; cmp.strExpr = 'baz';
detectChangesAndCheck(fixture, 'init baz'); detectChangesAndExpectClassName('init bar baz foo');
cmp.objExpr = null;
detectChangesAndExpectClassName('init baz');
})); }));
}); });
}); });
@ -384,8 +339,13 @@ class TestComponent {
items: any[]; items: any[];
arrExpr: string[] = ['foo']; arrExpr: string[] = ['foo'];
setExpr: Set<string> = new Set<string>(); setExpr: Set<string> = new Set<string>();
objExpr = {'foo': true, 'bar': false}; objExpr: {[klass: string]: any} = {'foo': true, 'bar': false};
strExpr = 'foo'; strExpr = 'foo';
constructor() { this.setExpr.add('foo'); } constructor() { this.setExpr.add('foo'); }
} }
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent);
}

View File

@ -149,18 +149,20 @@ export class StringMapWrapper {
} }
static equals<V>(m1: {[key: string]: V}, m2: {[key: string]: V}): boolean { static equals<V>(m1: {[key: string]: V}, m2: {[key: string]: V}): boolean {
var k1 = Object.keys(m1); const k1 = Object.keys(m1);
var k2 = Object.keys(m2); const k2 = Object.keys(m2);
if (k1.length != k2.length) { if (k1.length != k2.length) {
return false; return false;
} }
var key: any /** TODO #???? */;
for (var i = 0; i < k1.length; i++) { for (let i = 0; i < k1.length; i++) {
key = k1[i]; const key = k1[i];
if (m1[key] !== m2[key]) { if (m1[key] !== m2[key]) {
return false; return false;
} }
} }
return true; return true;
} }
} }

View File

@ -109,9 +109,9 @@ export declare class LowerCasePipe implements PipeTransform {
/** @stable */ /** @stable */
export declare class NgClass implements DoCheck { export declare class NgClass implements DoCheck {
initialClasses: string; klass: string;
ngClass: string | string[] | Set<string> | { ngClass: string | string[] | Set<string> | {
[key: string]: any; [klass: string]: any;
}; };
constructor(_iterableDiffers: IterableDiffers, _keyValueDiffers: KeyValueDiffers, _ngEl: ElementRef, _renderer: Renderer); constructor(_iterableDiffers: IterableDiffers, _keyValueDiffers: KeyValueDiffers, _ngEl: ElementRef, _renderer: Renderer);
ngDoCheck(): void; ngDoCheck(): void;