Search code examples
angular-dart

call async function from angular controller


I want to call an async function from angular form template controller. But if I do so, execution hangs.

Following the html template:

<div class="container">
    <form>
      <div class="form-group">
        <label for="address">Identnummer (Adresse)&nbsp;*</label>
        <input type="text" class="form-control" id="address" required placeholder="0x"
                    [(ngModel)]="model.address"
                    #address="ngForm"
                    [ngClass]="setAddressCssValidityClass(address)"
                    ngControl="address">
      </div>

      <div class="row">
        <div class="col-auto">
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
        <small class="col text-right">*&nbsp;Required</small>
      </div>
    </form>
  </div>

Here is a simplified version of my controller:

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'sCert-validate-form',
  templateUrl: 'sCert_validate_form_component.html',
  directives: [coreDirectives, formDirectives],
)
class ScertValidateFormComponent {

  Map<String, bool> setAddressCssValidityClass(NgControl control) {
    var validityClass;
    //callCertificateByAddress(control.value);
    if(control.value == "test"){
      validityClass = 'is-valid';
      callCertificateByAddress(control.value);      
    }
    else{
      validityClass = 'is-invalid';
    }
    Map<String, bool> map = {validityClass: true};
    return map;
  }

  Future<bool> callCertificateByAddress(String address) async {
    // some code -> also does not work if removed
    return true;
  }
}

Future<bool> callCertificateByAddress(String address) async has to be async, because I do async lib calls in there. But how can I achieve this in combination with the template?


Solution

  • there is a problem: you bind callback to the input here [ngClass]="setAddressCssValidityClass(address)" angular calls your function [which calls network] on each change detection cycle. and the response from http forces a new change detection which recursively calls http again and again. save the result to some variable and bind it to ngClass instead of a method

    ngOnInit() {
      this.classes = this.setAddressCssValidityClass(address);
    }
    ....
    [ngClass]="classes"