Search code examples
angularangular-components

How to hide child component content in the parent when data binding in Angular


I am new in Angular,i have two components, the parent component is Tasks to load user tasks and the child is ActionsComponent to load actions of tasks, I want to pass accountId and taskId fields from the parent to the child, so I added the ActionsComponent and used data binding to fill those variables.

Tasks:

    export class Tasks implements OnInit {

    accountId: string = '';
    taskId!: string;
....
}

Tasks HTML template:

<app-actions [accountId]="accountId"  [taskId]="taskId" ></app-actions>

<h3>Your Tasks</h3>
<table id="mat-table" mat-table [dataSource]="accountsTasks" class="mat-elevation-z8">
....
</table>

And this is app-actions HTML template to show those fields:

<h3> stringValue value: {{ stringValue }}</h3>
<h3> accountId value: {{ accountId }}</h3>

Tasks page: enter image description here

my problem is the entire content of the app-actions being displayed in the parent component page, i do not want to have child component content in the parent component, i want to just pass accountId and taskId fields to child and use them in child component, how can i do this without showing child component in the parent? TNX

Edit(Solution):
I used the route parameter to send the variable from the Task component to the Action component. i approved the solution.


Solution

  • From what I understood you want to separate the loading logic, for the tasks in separate component called app-actions that should not be rendered in the app-tasks.

    This is not possible with a component, as per definition components have a template that will be rendered.

    In order to achieve the behavior of splitting the loading logic I would suggest two different approaches.

    1. Create a service that will handle the loading logic and use it directly in the parent app-tasks.
    2. Create a directive and handle the loading logic in the directive, as directives are pretty much a component without template, so you won't see any html rendered in the parent component.

    Post edit:

    1. Attach the component to a separate route and you can use the route parameters. So you will have a path
    /actions/:accountId/:taskId
    

    after that, you can get the ID from the router.

    1. Pass the id-s through a shared service, then access the id-s from that shared service

    Side note: I will go for option 3 if I'm in your shoes.