Bird
0
0

Identify the error in this Angular component code:

medium📝 Debug Q14 of 15
Angular - Lifecycle Hooks
Identify the error in this Angular component code:
export class SampleComponent implements OnInit {
  message: string;
  ngOnInit() {
    this.message = 'Welcome';
  }
}
AngOnInit method name is incorrect
Bmessage property should be initialized in constructor
CMissing import of OnInit interface
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check for required imports

    The component implements OnInit but does not import it from '@angular/core'. This causes a compile error.
  2. Step 2: Verify method and property usage

    The method name ngOnInit is correct, and initializing message in ngOnInit is valid.
  3. Final Answer:

    Missing import of OnInit interface -> Option C
  4. Quick Check:

    Implementing OnInit requires importing it [OK]
Quick Trick: Always import lifecycle interfaces from '@angular/core' [OK]
Common Mistakes:
  • Forgetting to import OnInit
  • Renaming ngOnInit incorrectly
  • Thinking properties must initialize in constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes