angulartypescriptasync-awaitangular-promise

Calling function from HTML to typescript not waited to finish


I have an HTML element as bellow

<div *ngFor="let item of items">
    <input type='number' [min]="getMinData(param1,param2)" />
</div>

inside ts file

 getMinData(rules: ConstraintRule[], id: string) {
    rules.forEach((rule) => {
      rule._metadata.productList.forEach((product: SProduct) => {
        product.OptionGroups.forEach((optionGroup: SProductOptionGroup) => {
          optionGroup.Options.forEach((option: SProductOptionComponent) => {
            if (option.ComponentProductId == id) {
              return option.MinQuantity;
            }
          });
        });
      });
    });
  }

Also, there's no any API call or any other thing, it's just filtration over the local data.

But, On HTML correct qty is not returned.


Solution

  • You have to return something for getMinData function.

    Currently, you call return option.MinQuantity;, but it is result for an anonymous function - (option: SProductOptionComponent) => {.

    If you just want to find the first option.MinQuantity, try this function:

    getMinData(rules: ConstraintRule[], id: string) {
      let minQuantity = 0;
    
      rules.forEach((rule) => {
        rule._metadata.productList.forEach(({ OptionGroups }) => {
          OptionGroups.forEach(({ Options }) => {
            const foundOption = Options.find((o) => o.ComponentProductId === id);
            minQuantity = foundOption ? foundOption.MinQuantity : 0; // Default min value is 0
          });
        });
      });
    
      return minQuantity; // return value
    }