misha130
misha130

Reputation: 5706

Angular Component @Input is always empty on set

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?

Upvotes: 2

Views: 1445

Answers (1)

misha130
misha130

Reputation: 5706

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.

Upvotes: 1

Related Questions