Bird
0
0

This Angular component code has an error:

medium📝 Debug Q6 of 15
Angular - Lifecycle Hooks
This Angular component code has an error:
export class DemoComponent implements OnInit {
  ngOnInit() {
    console.log('Init');
  }
  ngOnDestroy() {
    console.log('Destroy');
  }
  ngOnInit() {
    console.log('Second Init');
  }
}

What is the problem?
AngOnInit should not have console.log
BngOnDestroy is missing interface implementation
CDuplicate ngOnInit method causes a syntax error
DNo errors, code is valid
Step-by-Step Solution
Solution:
  1. Step 1: Identify duplicate method definitions

    The component defines ngOnInit twice, which is not allowed in a class and causes a syntax error.
  2. Step 2: Check other options

    Missing interface for ngOnDestroy is not a syntax error; console.log is allowed; code is invalid due to duplicate method.
  3. Final Answer:

    Duplicate ngOnInit method causes a syntax error -> Option C
  4. Quick Check:

    Duplicate method names cause syntax errors [OK]
Quick Trick: No duplicate method names in a class [OK]
Common Mistakes:
  • Ignoring duplicate method error
  • Thinking missing interface causes syntax error
  • Assuming console.log is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes