X Tutup
Skip to content

Commit 045cc82

Browse files
fix(compiler): remove attributes when expression in [attr.foo]='exp' evaluates to null
Fixes #4150 Closes #4163
1 parent 9f999dd commit 045cc82

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

modules/angular2/src/core/compiler/view.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,8 @@ export class AppView implements ChangeDispatcher, RenderEventDispatcher {
183183
if (b.isElementProperty()) {
184184
this.renderer.setElementProperty(elementRef, b.name, currentValue);
185185
} else if (b.isElementAttribute()) {
186-
this.renderer.setElementAttribute(elementRef, b.name, `${currentValue}`);
186+
this.renderer.setElementAttribute(elementRef, b.name,
187+
isPresent(currentValue) ? `${currentValue}` : null);
187188
} else if (b.isElementClass()) {
188189
this.renderer.setElementClass(elementRef, b.name, currentValue);
189190
} else if (b.isElementStyle()) {

modules/angular2/test/core/compiler/integration_spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,30 @@ export function main() {
167167
});
168168
}));
169169

170+
it('should remove an attribute when attribute expression evaluates to null',
171+
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
172+
tcb.overrideView(MyComp,
173+
new ViewMetadata({template: '<div [attr.foo]="ctxProp"></div>'}))
174+
175+
.createAsync(MyComp)
176+
.then((rootTC) => {
177+
178+
rootTC.debugElement.componentInstance.ctxProp = 'bar';
179+
rootTC.detectChanges();
180+
expect(DOM.getAttribute(rootTC.debugElement.componentViewChildren[0].nativeElement,
181+
'foo'))
182+
.toEqual('bar');
183+
184+
rootTC.debugElement.componentInstance.ctxProp = null;
185+
rootTC.detectChanges();
186+
expect(DOM.hasAttribute(rootTC.debugElement.componentViewChildren[0].nativeElement,
187+
'foo'))
188+
.toBeFalsy();
189+
190+
async.done();
191+
});
192+
}));
193+
170194
it('should consume binding to property names where attr name and property name do not match',
171195
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
172196
tcb.overrideView(MyComp,

0 commit comments

Comments
 (0)
X Tutup