Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply async/await on @inputs in angular

Tags:

angular

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

like image 966
user3140824 Avatar asked Nov 07 '25 23:11

user3140824


1 Answers

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
      //...
    }
  }
}

like image 126
Thierry Falvo Avatar answered Nov 09 '25 14:11

Thierry Falvo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!