Currently, I am exploring Angular2 and have reached a point where I want to implement dynamic style extension in Angular2 components. To clarify things further, here is some code:
Main.ts
import {bootstrap} from 'angular2/platform/browser';
import {App} from './app'
bootstrap(App).then(error => console.log(error));
App.ts
import { Component } from 'angular2/core';
import { Button } from './button';
@Component({
selector: 'app',
template: `<button [style.background]="'green'">Hello World</button>`,
directives: [Button]
})
export class App { }
Button.ts
import {Component, Input, ElementRef, Renderer} from "angular2/core";
import {BrowserDomAdapter} from "angular2/src/platform/browser/browser_adapter";
@Component({
selector: 'button',
templateUrl: '<span [style.color]="test"><ng-content></ng-content></span>',
providers: [BrowserDomAdapter]
})
export class Button {
test: string;
constructor(private renderer:Renderer, private elementRef:ElementRef, dom: BrowserDomAdapter) {
let styles = elementRef.nativeElement.style;
console.log(styles);
this.test = styles['background'] || 'red';
console.log(this.test);
}
}
Now, onto something that could be considered a unique behavior. Just to note, I am not very experienced with DOM manipulations, but I have been stuck on this issue for hours without finding a solution.
When running this app, the following output is displayed in the console:
- CSSStyleDeclaration {...}
- red*
*The styles['background'] shows an empty string
However, in the CSSStyleDeclaration, 'background' is set as "green", as expected since it is an inline style.
To verify, I also tested it in different browsers (Chrome and Firefox only) and checked the 'style'-Property on this website(It works fine here):
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_get_elmnt
After all the testing, I was unable to find a suitable solution. Even using the BrowserDomAdapter did not work, as it utilized the same code to fetch the style properties.
Is this a bug within the Angular2 Framework? If so, has it been reported and are there any possible workarounds? If not, are there any alternatives or will there be changes in the future?
While this feature is not crucial, it would aid me in my work. I require this functionality because I am utilizing dynamically generated stylesheets, and users of my components should be able to override them using ngStyle and the '[style.property]' syntax of Angular2. Note that I prefer not to use the 'style'-Property of the Component-Decorator and simply override them for certain reasons.
Thank you for your assistance.