Search code examples
htmlcssangularng-class

angular 2+ component with attribute name and no parameters


I want to allow a user to provide a list of one-word attributes without parameter values. For example,

<container row crosscenter wrap spacearound ...>

which results in something like this in container.html

<div [ngClass]="{ 'flexDisplay': true, 'directionRow': isRow, 'directionCol': isCol, 'contentSpaceAround': isSpaceAround}" ...>

What I'm missing is how to set

@Input('row') isRow = false;

to true if 'row' was present in the container line.

Any ideas? Thanks in advance. Yogi


Solution

  • This can be handled in ngOnChanges. The value can be assigned either back to input property or to some object that will be passed to ngClass

    ngOnChanges(changes: SimpleChanges) {
      if ('foo' in changes) {
        this.options.foo = true;
      }
    }
    

    Since there's no way how inputs can become unassigned, there's no reason to provide bindings for them. @Attribute can be used instead:

    constructor(@Attribute('foo') public foo: boolean|null) {
      this.foo = (foo != null);
    }
    

    Using attributes for regular options isn't a good decision, design-wise. This prevents from setting them dynamically. Instead, it is always preferable to accept options input. If all options are supposed to be flags, it can be a string input that will be split and processed in ngOnChanges, like:

    <container options="row crosscenter wrap spacearound">
    

    or

    <container [options]="'row crosscenter wrap spacearound'">