简体   繁体   中英

How and when to bind a dropdownlist properly in Angular?

I use the following method for binding dropdownlists in Angular, but I think I make something wrong as I do not get the expected behaviour sometimes:

demoService.ts

getProducts(): Observable<ProductDto> { ... }

product.component.ts:

products: ProductDto[] = [];

ngOnInit(): void {
    this.bindProducts();
}

bindProducts() {
    this.demoService.getProducts()
    .subscribe((list: ProductDto) => {
        this.products = list;
    });
    //for testing purpose
    const check = this.products;
}

test() {
    this.bindProducts();
    //for testing purpose
    const test= this.products;
}

1. Is the list variable definition products: ProductDto[] = []; is correct? Or should I use some Observable parameter for that?

2. Should I populate the dropdownlists in ngAfterViewInit() instead of ngOnInit() ? in order to loading forms faster?

3. In the code above, I use subscribe method, but when binding list, I cannot make this.products to be filled in the test() method above. I think it is most probably subscribe method, but how can I make this variable to be filled later instead of onInit()? Should I use toPromise or something etc? What is the proper way?

There is no 'proper' way just 'better' way 'recommended' way and 'preferential' way.

Below is how I would approach it

product.component.ts:


export ProductComponent {
  products$ = this.demoService.getProducts();
}

Yes, I have removed OnInit life cycle hook and all other codes. I even have not declared the type of products$ as typescript will infer this.

In my component I can then use async pipe

<ng-container *ngIf='products$ | async as products'>
  <!-- My code here -->
</ng-container>

Basically we allow angular do the heavy lifting stuff like subscribing and unsubscribing for us.

You can have a look at this sandbox demo

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