2

I have a component that has 2 inputs, one is set and one is a regular property.

@Input() public set value(val: string) {
        this._selectedOption =
           this._options.find(o => o[this.selectedProperty || 'someDefault'] === val);
    }
@Input() public selectedProperty: string;

In the above code, the selectedProperty is always empty the first time there is a set value.

This is the html:

 <my-component [value]="someValue"
                           selectedProperty="value"
                </my-component>

In other appearances of this component the selectedProperty will be empty.

How do I make the selectedProperty not be empty the first time?

3
  • For me has no sense, it work, see stackblitz.com/edit/…. Are you sure "somevalue" is a variable of parent? Remember that if you write [value]="expresion", the expresion is a variable or a constant type 'value' Commented May 7, 2019 at 7:10
  • I couldn't run the stackblitz but yes, 'someValue' was a property(variable) that holds a string in the parent. I would suggest to edit the stackblitz to console log the selectedProperty in the set of value to see if its undefined and it should be. Commented May 7, 2019 at 12:38
  • 1
    Sorry, @misha, it's true, please forget my comment, the only solution is change the order of the declarations Commented May 7, 2019 at 13:16

1 Answer 1

1

A fun answer. The order of sets in the @Inputs are the order of their declaration in the class.

So to have selectedProperty set first it should be:

@Input() public selectedProperty: string;
@Input() public set value(val: string) {
        this._selectedOption =
           this._options.find(o => o[this.selectedProperty || 'someDefault'] === val);
    }

This is generally related to how JavaScript works and in general this is the order of how angular finds the inputs in the class.

Sign up to request clarification or add additional context in comments.

2 Comments

Or don't expect it to be set on property setters. Move the code to a method and call it on init and also when set after init.
Would have to move the code to be an ngmodel kind of thing rather than nginit since it needs to execute each time the value changes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.