4

An input is being executed first and so the value of this._settings is still null as to leave asynchronously so that you first execute the settings and then execute the data

edit: If I apply a timeout on the data even if it is with value 1 it will work normally

// should be the first
@Input()
  public set settings(value) {
    if (value) {
      this._settings = Object.assign(this.defaultSettings, value);
    } else {
      this._settings = Object.assign(this.defaultSettings);
    }
  }

  @Input()
  public set data(value: Array<any>) {
    if (!value) {
      this._data = [];
    } else {
      this._data = value.map((item: any) =>
        typeof item === 'string' || typeof item === 'number'
          ? new ListItem(item)
           : new ListItem({
          id: item[this._settings.idField],
          text: item[this._settings.textField],
        })
      );
    }
  }

Thank you for your help

2
  • 1
    If you can't do async await on setters, maybe you should look into the ngOnChanges lifecycle hook. It's a hook that runs every time an @Input() changes. And I am sure you can do async await there. Commented Mar 4, 2020 at 19:13
  • Please provide an minimal reproducible example, the code you have shared does not illustrate the problem. The only other issue I see here is that you have 2 inputs that are dependent on each other. That would be best moved into an event like ngOnInit and let the inputs just be simple atomic setters/getters. Commented Mar 4, 2020 at 20:13

1 Answer 1

2

In your example, you have 2 @Input properties which are dependent on each other.

In this case, a good practice could be to implement OnChanges interface on your component, and move your logic inside ngOnChanges method implementation. You will be able to treat the different situation depending on current value of properties. My advice is also to keep separated a third computed value, which will be the result of your logic code.

export class MyComponent implements OnChanges {
  @Input settings: SettingsType;
  @Input data: DataType;

  computedData: DataType = [];

  ngOnChanges(changes: SimpleChanges): void {

    // logic
    if (!this.data || !this.settings) {
      this.computedData = [];
    } else {
      // here `data` and `settings` are defined
      //...
    }
  }
}

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

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.