How to use @Input decorator in Angular
Using the @Input decorator is fundamental for creating reusable Angular components that accept data from parent components and establish proper data flow patterns. As the creator of CoreUI, a widely used open-source UI library, I’ve designed thousands of Angular components using @Input decorators for flexible customization, configuration options, and data binding in enterprise component libraries. From my expertise, the most robust approach is to use @Input decorator with TypeScript typing and proper validation. This method provides type safety, clear component interfaces, and excellent developer experience while maintaining backward compatibility and component reusability.
Use @Input()
decorator to mark component properties as bindable from parent components.
import { Component, Input, OnChanges } from '@angular/core'
@Component({
selector: 'app-button',
template: `
<button
[class]="buttonClasses"
[disabled]="disabled"
(click)="onClick()">
{{ label }}
</button>
`
})
export class ButtonComponent implements OnChanges {
@Input() label: string = 'Click me'
@Input() variant: 'primary' | 'secondary' | 'danger' = 'primary'
@Input() size: 'sm' | 'md' | 'lg' = 'md'
@Input() disabled: boolean = false
get buttonClasses(): string {
return `btn btn-${this.variant} btn-${this.size}`
}
ngOnChanges() {
// React to input changes if needed
}
onClick() {
if (!this.disabled) {
// Handle click logic
}
}
}
// Usage in parent template:
// <app-button label="Save" variant="primary" size="lg" [disabled]="isLoading"></app-button>
The @Input()
decorator marks class properties as input properties that can receive data from parent components through property binding. Use TypeScript types to define the expected data structure and provide default values for optional inputs. Parent components bind to input properties using square bracket syntax [propertyName]="value"
. Implement OnChanges
interface to react to input property changes. This creates a clean API for component customization and enables component reusability across different contexts.
Best Practice Note:
This is the same approach we use in CoreUI Angular components for flexible and type-safe component APIs. Use readonly inputs when possible, validate input values in ngOnChanges, and consider using getters for computed properties based on inputs. Always provide default values and use union types for constrained input options.