简体   繁体   中英

Property using child component in Angular?

How to decide when to use child angular component inside parent?

Should it be one entity, for example lessons list and add lesson.

I try to get when I should use child component, when exist real relation between parent and child?

Lets assume we have product card with buttons inside:

<app-product-card>
    <!-- Product information here -->
    <app-product-buttons></app-product-buttons>
</app-product-card>

On of button app-product-buttons has clic event, that shows list of users, who bought this product.

Should I insert <app-users-producst-buy></app-users-producst-buy> inside:

  <app-product-card>
        <!-- Product information here -->
        <app-product-buttons [product]="product"></app-product-buttons>
        <app-users-producst-buy></app-users-producst-buy>
    </app-product-card>

Or inside as child in buttons component:

  <app-product-card>
        <!-- Product information here -->
        <app-product-buttons>
               <app-users-producst-buy [product]="product"></app-users-producst-buy>
        </app-product-buttons>
    </app-product-card>

How to make a right decicion on this cases? Or should I use dynamic components?

From my experience with Angular framework, this decision is no always easy as you are saying.

Moreover, you can apply that kind of rules:

1) Modularity: I always use child component when the child component I am about to design will appear in more than one place in the project.

2) Maintainability: The simpler, the more maintainable. When a component tends to be huge, and you can identify several sub-components, let's split it.

3) DRY (Don't Repeat Yourself): thinking in small, specialised components (without going into the excess, for sure) can be a key to keep a small but very functional code-base.

I hope these points can help you making decisions.

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