This post shows how to pass data from one component to another in Angular using @Input. Also, we embed a component’s selector in another component’s HTML. Therefore, in that sense, we are passing data from a parent to a child component. We are not discussing URLs and redirects.
We have migrated the codes from Angular 7.20 to 15.0.0.
Angular Requirements
- Angular CLI 15.0.4
- NPM 8.19.2
- Node 18.12.1
- Internet connection
Create a new Component in Angular
This part assumes that we have an existing fresh application generated via
1 | ng new [project name] |
To create a new component, use the following:
1 | ng g c child |
Next, we need a new property in the child component to store any value from the app (parent) component.
1 2 3 | ... @Input('paramChildDetails') childDetails: {name?: string, description?: string} = {}; ... |
We need to decorate property childDetails @Input(‘parameterChildDetails’). The ‘parameterChildDetails‘ is how ‘childDetails‘ is referred to or known outside the component.
Pass Data from Parent Component
In app.component.html, we pass values as follows:
1 2 3 4 | <div style="text-align:center"> <app-child [paramChildDetails]="{name:'child1', description: 'description of child 1'}"></app-child> <app-child [paramChildDetails]="{name:'child2', description: 'description of child 2'}"></app-child> </div> |
The Angular application does a one-way data transfer – from parent to child component. However, we can also do the other way – pass data from the child to the parent component!
Test Angular Pass Data Component
The page looks like this:
Download the Files
We have migrated the codes to Angular 15. Please check the codes out on our GitHub account.