1

I have a form array of cars and an API that gives me a list of cars. Is it a good practice to use async pipe inside of *ngFor or should I use subscribe instead?

<div class="container">
  <form [formGroup]="form">
    <button
      type="button"
      (click)="getCars().push(createCars())"
      class="btn btn-primary btn-sm"
    >
      add Cars
    </button>
    <div
      formArrayName="cars"
      *ngFor="let h of getCars()!.controls; let indexCars = index;"
    >
      <div class="form-group col-md-12">
        <select [formControlName]="indexCars" id="cars" class="form-control">
          <option *ngFor="let data of (cars$ | async)" [ngValue]="data">
            {{ data | json }}
          </option>
        </select>
      </div>
    </div>
  </form>
</div>
export class AppComponent {
  cars$: Observable<string[]>;
  listCars: string[] = [];
  form: FormGroup;
  formBuilder: FormBuilder = new FormBuilder();
  constructor() {
    this.cars$ = this.getCars$();
    this.form = this.formBuilder.group({
      cars: this.formBuilder.array([
        this.createCars(),
        this.createCars(),
        this.createCars(),
      ]),
    });
  }

  getCars(): FormArray {
    return this.form.get('cars') as FormArray;
  }

  createCars() {
    return this.formBuilder.control('', []);
  }

  getCars$() {
    return of(['car 1', 'car 2', 'car 3', 'car 4']).pipe(delay(3000));
  }
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
carlos
  • 591
  • 1
  • 5
  • 15
  • 1
    I'd actually prefer using the `async` over the manual subscription due to it's "garbage collection" feature. `async` unsubscribes or closes the open subscription when the corresponding component is closed. On the other hand with manual subscription, [manual clean up](https://stackoverflow.com/a/60223749/6513921) is required. – ruth Nov 19 '21 at 15:57
  • `| aynsc` is fine inside `*ngFor`. I suggest you read [this decent article](https://medium.com/angular-in-depth/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794) if you want to understand why favor one instead of another. – Florian Nov 19 '21 at 16:10

0 Answers0