Parent to Child Data Passing - Input Decorator - Signals
Parent and Child Component Concept
In Angular, the whole project is not made inside one component.
Different parts like header, footer, list, search box are made as separate components.
This helps to keep code small, clean, and reusable.
Why Child Component Is Needed
If all code is written in one component, the file becomes very large.
A child component helps to reuse the same UI and logic multiple times.
Data usually stays in the parent component and is passed to the child.
Creating Child Component
A child component is created using the Angular generate component command.
It creates four files: HTML, CSS, TS, and spec file.
The selector of the child component is used inside the parent HTML.
Using Child Component in Parent
The child component selector is written in the parent HTML file.
The child component is also imported in the parent TS file.
After this, the child component works properly.
Passing Data from Parent to Child
The data exists in the parent component.
Property binding is used to send data to the child component.
Receiving Data in Child Component
The child component receives data using @Input() decorator.
The same property name is used in the child component.
The received data is used directly in child HTML without signal brackets.
Using Child Component in Loop
Multiple users are stored in an array signal in the parent component.
The @for loop is used to loop through users.
Each user value is passed to the child component.
Styling in Child Component
The data is displayed inside an li tag.
A CSS class is applied to style the list items like border, padding, and width.
Adding New User with Input and Button
An input field is used to type a new user name.
The input event updates the newUser signal.
A button click calls a function to add the new user.
Updating Users List
The addNewUser function updates the users array using signal update.
Old users remain and the new user is added at the end.