All quizzesMedium
Lifecycle & Projection
Preview — 3 of 10 questions
What is the key difference between constructor and ngOnInit in an Angular component?
javascript
@Component({ selector: 'app-user', template: '...', standalone: true })
export class UserComponent implements OnInit {
@Input() userId!: string;
user?: User;
constructor(private userService: UserService) {
// ✅ inject service
// ❌ this.userId is undefined here
}
ngOnInit() {
// ✅ this.userId is now set
this.userService.getUser(this.userId).subscribe(u => this.user = u);
}
}AThe constructor runs after change detection; ngOnInit runs before
BngOnInit only runs once; the constructor can run multiple times
CThe constructor is for DI and basic setup; ngOnInit runs after inputs are set and is the right place for initialization logic
DThere is no practical difference — use whichever you prefer
How do you pass data from a parent component to a child component in Angular?
javascript
// child.component.ts
@Component({
selector: 'app-badge',
template: `<span>{{ label }}</span>`,
standalone: true,
})
export class BadgeComponent {
@Input({ required: true }) label!: string;
@Input() color = 'blue';
}
// parent.component.ts
@Component({
selector: 'app-parent',
template: `<app-badge [label]="'Pro'" [color]="'gold'" />`,
standalone: true,
imports: [BadgeComponent],
})
export class ParentComponent {}AUsing a shared service with a BehaviorSubject
BDecorating a child property with @Input() and binding to it in the parent's template
CUsing the @Output() decorator on the parent
DAccessing the parent component via ViewChild
How does a child component notify its parent of an event?
javascript
// child.component.ts
@Component({
selector: 'app-like-button',
template: `<button (click)="like()">Like</button>`,
standalone: true,
})
export class LikeButtonComponent {
@Output() liked = new EventEmitter<void>();
like() {
this.liked.emit();
}
}
// parent.component.ts
@Component({
selector: 'app-post',
template: `<app-like-button (liked)="onLiked()" />`,
standalone: true,
imports: [LikeButtonComponent],
})
export class PostComponent {
onLiked() { console.log('Post liked!'); }
}ABy directly calling a method on the parent component's instance
BBy decorating a property with @Output() using an EventEmitter and calling .emit()
CBy dispatching a native DOM CustomEvent
DBy modifying a shared object passed via @Input()
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.