简体   繁体   中英

angular: how to handle async pipes correctly

I would like to display all users after all controls were added to the ProfileForm. That´s why I tried using the async pipe on my observable users$. But obviously it displays the users before all controls were added and not after. How do I wait until all controls are added?

ts:

profileForm = this.fb.group({
    name: []
});

users$: Observable<Users[]>;


ngOnInit(): void {
    this.users$ = this.userService.getAllUsers();

    this.users$.forEach(user =>
        this.profileForm.addControl(`user_${user.id}`, this.fb.control(id));
    );
}

html:

<mat-expansion-panel *ngFor="let user of users$ | async">
    <mat-expansion-panel-header>
        <mat-panel-title>
            <mat-checkbox [formControlName]="'user_' + user.id"></mat-checkbox>
            <span>{{ user.name }}</span>         
        </mat-panel-title>
    </mat-expansion-panel-header>
</mat-expansion-panel>

you can do it like this:

this.users$ = this.userService.getAllUsers().pipe(
   tap(users => {
        users.forEach(user =>
        this.profileForm.addControl(`user_${user.id}`, this.fb.control(id));
    );
   })
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM