Angular Web Framework Components & Templates 2 — Questions and Answers
Question 1: Which lifecycle hook is called after Angular projects external content into the component's view?
- ngOnInit
- ngAfterViewInit
- ngAfterContentInit (Correct answer)
- ngOnChanges
Correct answer: ngAfterContentInit
ngAfterContentInit fires after Angular finishes projecting external content (ng-content) into the component.
Question 2: What does the `host` property in a @Component decorator allow you to configure?
- Child component selectors
- Host element bindings and listeners (Correct answer)
- Dependency injection tokens
- Template URL paths
Correct answer: Host element bindings and listeners
The `host` property maps DOM events and property bindings directly onto the component's host element.
Question 3: In Angular, what is the purpose of `ng-content` with a `select` attribute?
- To conditionally render a template block
- To project only matching elements from the parent (Correct answer)
- To define a named router outlet
- To select a CSS class for the host element
Correct answer: To project only matching elements from the parent
The `select` attribute on ng-content acts as a CSS selector to filter which projected content goes into that slot.
Question 4: Which change detection strategy checks a component only when its inputs change or an event fires from within it?
- Default
- OnPush (Correct answer)
- Detached
- Manual
Correct answer: OnPush
ChangeDetectionStrategy.OnPush limits checks to when @Input references change or internal events occur, improving performance.
Question 5: What Angular decorator would you use to expose a DOM event from a child component to its parent?
- @Input
- @HostListener
- @Output (Correct answer)
- @ViewChild
Correct answer: @Output
@Output combined with EventEmitter lets a child emit events that the parent can listen to with event binding syntax.
Question 6: How do you bind to a custom property called `isActive` on a child component in a parent template?
- (isActive)="value"
- {{isActive}}
- [isActive]="value" (Correct answer)
- #isActive="value"
Correct answer: [isActive]="value"
Square bracket syntax [isActive]="value" is property binding, which passes a value into a child component's @Input.
Question 7: What is the effect of marking a component's @Input with `{ required: true }` in Angular 16+?
- It throws a runtime error if omitted
- It generates a compile-time error if the input is not supplied (Correct answer)
- It defaults the value to null
- It makes the property read-only
Correct answer: It generates a compile-time error if the input is not supplied
Angular 16 introduced required inputs that produce a compile-time diagnostic when a parent template omits the binding.
Which lifecycle hook is called after Angular projects external content into the component's view?