Bird
0
0

What will happen when this directive is applied?

medium📝 component behavior Q5 of 15
Angular - Directives
What will happen when this directive is applied?
@Directive({ selector: '[appClick]' })
export class ClickDirective {
  constructor(private el: ElementRef) {
    this.el.nativeElement.addEventListener('click', () => alert('Clicked!'));
  }
}

Applied as: <button appClick>Press</button>

AAn alert 'Clicked!' shows when button is pressed
BNothing happens on click
CError because Renderer2 is missing
DThe button text changes to 'Clicked!'
Step-by-Step Solution
Solution:
  1. Step 1: Understand event listener attachment

    The directive adds a native click event listener that triggers an alert with 'Clicked!'.
  2. Step 2: Confirm behavior on button click

    Clicking the button triggers the alert as expected.
  3. Final Answer:

    An alert 'Clicked!' shows when button is pressed -> Option A
  4. Quick Check:

    Native event listener triggers alert = A [OK]
Quick Trick: Directives can add native event listeners via ElementRef [OK]
Common Mistakes:
  • Expecting Renderer2 is mandatory for events
  • Assuming no effect without @HostListener
  • Thinking button text changes automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes