FresherCodingAngular
How do you pass data from a parent to a child component with input()?
Try answering first
Model answer
The child declares an input with the input() function, and the parent binds a value to it with square brackets. The input is a signal, so the child reads it by calling it.
import { Component, input } from '@angular/core'
@Component({
selector: 'app-user-card',
template: `<h3>{{ name() }}</h3>`,
})
export class UserCard {
name = input.required<string>()
}
@Component({
selector: 'app-root',
imports: [UserCard],
template: `<app-user-card [name]="userName" />`,
})
export class App {
userName = 'Linh'
}
Steps to remember:
- Import the child component in the parent's
imports. - Use
[name]="expression"for dynamic values, orname="Linh"for a plain string. - Read the input with
name(). The child cannot change it, because data flows down.
Older code uses the @Input() decorator instead. It still works, but new code should use input().
Data flows down through inputs and events flow up through outputs.
Key points
- input() declares a signal input in the child
- The parent binds it with square brackets
- Read the value by calling name()
- The child component must be in the parent imports
Likely follow-ups
- How does the child send a value back to the parent?
Common mistakes
- Forgetting to import the child component in the parent
- Writing name instead of name() in the template