constructor là của class TypeScript, chạy khi Angular tạo instance — lúc này @Input() chưa được gán. ngOnInit là lifecycle hook của Angular, chạy sau lần ngOnChanges đầu tiên, tức là input đã sẵn sàng.
ts
export class UserCard implements OnInit {
@Input() userId!: string
private http = inject(HttpClient)
user?: User
constructor() {
console.log(this.userId) // undefined — input not bound yet
}
ngOnInit() {
this.http.get<User>(`/api/users/${this.userId}`).subscribe(u => (this.user = u))
}
}Quy tắc thực tế:
- constructor: chỉ nhận dependency (hoặc dùng inject()) và gán field đơn giản. Không gọi API, không đụng DOM.
- ngOnInit: khởi tạo dựa trên input — gọi API, set up form, subscribe.
- Cần DOM đã render (đo kích thước, focus) thì phải đợi ngAfterViewInit.
Giữ constructor mỏng cũng giúp unit test dễ hơn: tạo component không kéo theo side effect.