Bird
0
0

Given this Angular component code:

medium📝 component behavior Q13 of 15
Angular - Services and Dependency Injection
Given this Angular component code:
@Component({
  selector: 'app-example',
  template: `

{{counter}}

`, providers: [CounterService] }) export class ExampleComponent { counter = 0; constructor(private counterService: CounterService) { this.counter = this.counterService.increment(); } }

If two instances of app-example are rendered, what will be the value of counter in each?
ABoth will show 0 because service is not provided.
BBoth will show the same incremented value shared globally.
CBoth will show 1 because each has its own service instance.
DBoth will show an error because service is missing.
Step-by-Step Solution
Solution:
  1. Step 1: Understand component-level service scope

    Providing CounterService in providers inside the component creates a new instance per component.
  2. Step 2: Analyze two component instances

    Each component instance gets its own service instance, so each counter starts fresh and increments once to 1.
  3. Final Answer:

    Both will show 1 because each has its own service instance. -> Option C
  4. Quick Check:

    Component scope = separate service instances per component [OK]
Quick Trick: Component providers create separate service instances per component [OK]
Common Mistakes:
MISTAKES
  • Assuming service is shared globally despite component providers
  • Thinking service is not provided at all
  • Confusing component scope with root scope

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes