Prepare for Angular Interviews with real-life questions. Utilize quizzes and examples to deepen understanding and enhance your skills. Gear up to ace your interview!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


Which directive is used for dynamically applying styles based on a condition?

  1. ngFor

  2. ngIf

  3. ngStyle

  4. ngModel

The correct answer is: ngStyle

The choice of ngStyle is accurate because this directive is specifically designed to dynamically apply styles to HTML elements based on a condition or an expression evaluated in your Angular component. With ngStyle, you can bind an object where the keys are CSS property names and the values are the corresponding styles you wish to apply. This allows for easy manipulation of styles based on conditional logic, such as user interactions or component states. For instance, you might use ngStyle to change the background color of a button based on whether it is active or disabled. This dynamic approach gives developers the flexibility to create responsive and visually-rich interfaces. In contrast, ngFor is used for rendering lists by iterating through an array or collection, ngIf is intended for conditionally including or excluding elements from the DOM based on a boolean expression, and ngModel is primarily used for two-way data binding between form input elements and the component properties. Each of these directives serves different purposes in Angular, making ngStyle the right choice for conditional styling.