2

Background

I have a component that wraps two span elements. I would like parent components to be able to style the inner two spans by specifying CSS classes and styles as inputs (preferably as simple strings). Here's a simplified example of what I would like this to look like:

Code

app component (parent)

@Component({
  selector: 'my-app',
  template: `
    <div>
      <app-two-spans [classArg1]="'class1'" [classArg2]="'class2'"
                     [styleArg1]="'width: 100px'" [styleArg2]="'width:200px'"></app-two-spans>
    </div>
  `, style: `
    ::ng-deep .class1 {
      border: 1px solid black;
    }
    ::ng-deep .class2 {
      border: 1px solid blue;
    }
  `
})
export class App {

}

two spans component (child)

import {Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'app-two-spans',
    template: `
        <span *ngIf="flag" [ngClass]="classArg1" [ngStyle]="styleArg1" 
              (click)="flag = !flag">click me</span>
        <span *ngIf="!flag" [ngClass]="classArg2" [ngStyle]="styleArg2" 
              (blur)="flag = !flag" contenteditable="true">
              click me to change my value</span> 
    `
})
export class TwoSpansComponent {
  flag: boolean = true;
  @Input() styleArg1: string;
  @Input() styleArg2: string;
  @Input() classArg1: string;
  @Input() classArg2: string;
  constructor() {}
}

Problem

The class styling seems to work in my local environment (though it doesn't seem to work on Plunker for some reason). However, the styles are not showing up. I've seen other posts about styles as inputs, but from what I've seen this is usually done by passing style-value pairs (see accepted answer here). However, I would really like to pass these styles as a simple string to make working with the component easier. I notice the following error in the console: ERROR Error: Cannot find a differ supporting object 'width: 100px'. I'm not sure what this means at all.

Plunker here

Is there a way to do this? How can I give parent components the ability to stylize children?

Andrew Kolos
  • 113
  • 8

1 Answers1

1

ngStyle accepts an Object instead of plain string. You can pass your styles as:

[styleArg1]="{ width: '100px' }"
[styleArg2]="{ width: '200px' }"
FAISAL
  • 33,618
  • 10
  • 97
  • 105
  • Hmm this could a good place to start. Perhaps I can write a function using a regex that converts plain css strings to such an object, so that I can write `[styleArg1]=" 'width: 100px' " as desired` – Andrew Kolos Aug 13 '17 at 16:11