0
0
Angularframework~10 mins

Access modifiers in components in Angular - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the property accessible only within the component class.

Angular
export class MyComponent {
  [1] title = 'Hello Angular';
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Using public makes the property accessible everywhere.
Using readonly only prevents changes but does not restrict access.
2fill in blank
medium

Complete the code to allow the property to be accessed by this class and its subclasses.

Angular
export class BaseComponent {
  [1] data = 42;
}

export class ChildComponent extends BaseComponent {
  showData() {
    console.log(this.data);
  }
}
Drag options to blanks, or click blank then click option'
Aprivate
Bprotected
Cpublic
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Using private hides the property from subclasses.
Using public exposes the property everywhere.
3fill in blank
hard

Fix the error in the code by choosing the correct access modifier for the method used in the template.

Angular
export class MyComponent {
  [1] getMessage() {
    return 'Welcome!';
  }
}

<!-- In template -->
<p>{{ getMessage() }}</p>
Drag options to blanks, or click blank then click option'
Apublic
Bprotected
Creadonly
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using private or protected hides the method from the template.
Readonly is not an access modifier for methods.
4fill in blank
hard

Fill both blanks to declare a property that can be read publicly but only set privately.

Angular
export class UserComponent {
  [1] _name = 'Alice';

  [2] get name() {
    return this._name;
  }
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Making the field public allows external code to change it.
Making the getter private hides it from outside.
5fill in blank
hard

Fill all three blanks to create a component with a protected method, a private property, and a public getter.

Angular
export class ProfileComponent {
  [1] _age = 30;

  [2] get age() {
    return this._age;
  }

  [3] updateAge(newAge: number) {
    this._age = newAge;
  }
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Making the method public exposes it everywhere.
Making the getter private hides it from templates.
Making the property public allows unwanted changes.