Bird
0
0

Consider the following Angular code snippet:

medium📝 component behavior Q4 of 15
Angular - Advanced Patterns
Consider the following Angular code snippet:
const compRef = viewContainerRef.createComponent(UserCardComponent);
compRef.instance.userName = 'Alice';
compRef.changeDetectorRef.detectChanges();

If UserCardComponent template contains <h1>{{ userName }}</h1>, what will be rendered in the DOM?
AAn error because userName is not a valid property
BNo output because change detection was not triggered
C<h1>Alice</h1>
DEmpty <h1></h1> since instance properties are not bound
Step-by-Step Solution
Solution:
  1. Step 1: Create component instance

    The createComponent method creates an instance of UserCardComponent.
  2. Step 2: Set input property

    Assigning userName = 'Alice' sets the component's property.
  3. Step 3: Trigger change detection

    Calling compRef.changeDetectorRef.detectChanges() updates the view to reflect the new property value.
  4. Final Answer:

    <h1>Alice</h1> -> Option C
  5. Quick Check:

    Property set + detectChanges = updated DOM [OK]
Quick Trick: Always call detectChanges after setting inputs dynamically [OK]
Common Mistakes:
  • Forgetting to call detectChanges after setting inputs
  • Assuming inputs update automatically without change detection
  • Confusing instance properties with template variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes