1

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

2 Answers 2

1

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'">
Sign up to request clarification or add additional context in comments.

3 Comments

I like your answer. In particular using the options = approach. The thing I don't understand is how this will cause and onChanges event to occur. Can you help me understand that?
Changes in @Input prop are handled with angular.io/api/core/OnChanges hook. If you set component options input, the value can be watched in ngOnChanges hook. It will run at least once with initial options value.
Thanks estus. I think the thing that really made this the right answer is the fact that it does run at least once with the initial options. I appreciate your help. :-)
0

I think the answer to my question is to create directives for each of the "one-word" tags (attributes) I want to use. :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.