0

I am trying to create generic controls like this

dynamic-control.ts

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

@Component({
  selector: 'ngo-button',
  template: `<button [ngClass]=class type={{type}}>{{message}}</button>`,
  styles: [`.one{border:solid 2px yellow} .two{background-color:pink} .three{
  background-color: blue;
}`]
})
export class HelloComponent  {
   @Input() type: string = 'button';
  @Input() class: string = 'one three';
  @Input() message: string = 'submit';
}

main-component.html

<ngo-button [class]='btn two' (click)='somefunc()'></ngo-button>

now i want to pass two classes to the button, but when i am trying to pass it this way, i am getting error

[class]='btn two'

i suppose, we are not allowed to add space in the input parameter, is there another way to implement it?

this is the stackblitz link

Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85

3 Answers3

8
<ngo-button [class]="'btn two'" (click)='somefunc()'></ngo-button>

Default syntax of Angular. You have to provide a string in quotes if you use the [input] notation.

Otherwise :

<ngo-button class="btn two" (click)='somefunc()'></ngo-button>

Although I have to say, it really don't understand why you use an input to provide the classes of your component.

2

You can use [ngClass]

<ngo-button [ngClass]="{'first class':{expression},'second class':{expression}}" (click)='somefunc()'></ngo-button>

N.B: expressions are like : true/false, 2>1 etc.

remember : remove the {} of {expression}

Azizul Hoq
  • 589
  • 1
  • 4
  • 13
  • This will not result in the same behaviour as the question asked, as the classes are applied to the host element `` instead of the internal template ` – LHSnow Jun 19 '19 at 09:23
0

If you use square brackets [] in Angular, you're telling the Angular compiler that what follows is an expression to be parsed. Since btn two isn't a valid expression, you're getting a parsing error. What you actually want to do is:

[class]="'btn two'".

It's worth mentioning that because you've chosen to name your input 'class,' you may potentially have issues later on with Angular both passing your values in as an input parameter and applying the value as a class to the parent element.

8ytan
  • 300
  • 1
  • 7
  • You provided another wrong syntax (also, consider upvoting an existing answer instead of parroting it) –  Jun 19 '19 at 09:05
  • @Maryannah Your answer wasn't there when I commented. It appeared only when I refreshed. – 8ytan Jun 19 '19 at 09:14
  • sure, I understand, then you wouldn't mind deleting it :) anyway, keep it if you want, I'm only giving you the best practices to adopt on stack overflow –  Jun 19 '19 at 09:15