Tech Point Fundamentals

Saturday, October 14, 2023

Angular Interview Questions and Answers - Part 04

Angular Interview Questions and Answers - Part 04

Angular-Interview-Questions-And-Answers

Angular is a popular open-source single-page application design framework and development platform. It is a robust front-end JavaScript framework that is widely used for front-end application development. Nowadays Angular is very famous as a frontend technology so it is very common for the interview point as well. 



Introduction


This is the Angular Interview Questions and Answers series. Here we will see 200+ Most Frequently Asked Angular Interview Questions. This is the 4th part of the Angular Interview Questions and Answer series.

I will highly recommend that please visit the following parts before continuing to this part:


Please do visit our YouTube Channel here to watch Interview Questions & Answers and important technology videos.



In this part we will discuss the following Important Angular Interview Questions:

Q039. What is the difference between SASS vs. SCSS stylesheet preprocessors in Angular?
Q040. What is View Encapsulation in Angular? How does View Encapsulation work in Angular?
Q041. Why the isolated CSS is required per Angular Components?
Q042. What are the different View Encapsulation provided by Angular?
Q043. What is Emulated ViewEncapsulation in Angular?
Q044. What is ShadowDom ViewEncapsulation in Angular?
Q045. What is None ViewEncapsulation in Angular?
Q046. What is the difference between CSS vs. ngClass vs. ngStyle in Angular?
Q047. What is NgClass Directive in Angular?
Q048. What is the NgStyle Directive in Angular?



Angular Interview Questions and Answers: Part 04


Q039. What is the difference between SASS vs. SCSS stylesheet preprocessors in Angular?

Both SASS and SCSS are very popular and widely used CSS preprocessors. However one follows indented syntax that has fewer rules and constraints, and the other follows a strict syntax that relies on braces and semicolons.

  1. SASS stands for Syntactically Awesome Style Sheets while SCSS stands for Sassy CSS.
  2. SASS files have a .sass extension while others have the .scss extension.
  3. SASS uses SassScript while SCSS uses only normal CSS i.e. no script.
  4. SASS is a quite popular CSS preprocessor. On the other hand, SCSS is a newer SASS syntax.
  5. SASS uses an indented syntax that is similar to Haml. On the other hand, SCSS uses CSS-like block formatting.


  6. CSS can not be used as SASS and vice-versa. While a valid CSS code is a valid SCSS code.
  7. SASS is backed by a huge community of contributors and developers. While SCSS has a small community and fewer contributors as it is new in the market.
  8. SASS supports SassDoc for adding documentation or comments. In contrast, SCSS allows inline documentation i.e. you can add comments in the SCSS code.
  9. SASS has fewer syntax constraints and rules. SASS has a loose syntax that uses no semicolons and has a lot of white space. On the other hand, SCSS is more expressive and syntax-oriented. SCSS is more like CSS, and therefore, semicolons and brackets are required.
  10. It is difficult to add SASS to existing CSS projects; Code rewriting is required in order to integrate with Existing CSS Projects. On the other hand, SCSS is easy to add to an existing CSS project by adding new code. Hence, code rewriting isn’t required.
  11. Although SASS supports a nesting feature to nest the CSS selectors to display in the HTML, it becomes difficult to maintain longer hierarchical nested CSS. On the other hand, SCSS can efficiently handle multiple classes and various nested styles.



Q040. What is View Encapsulation in Angular? How does View Encapsulation work in Angular?

One of the fundamental concepts in object-oriented programming (OOP) is Encapsulation. The View Encapsulation in Angular is a strategy that determines how angular hides (encapsulates) the styles defined in the component from bleeding over to the other parts of the application. It defines how the styles defined in the template affect the other parts of the application.

In the case of Angular apps, the components co-exist with the other components. Hence it becomes very important to ensure that the CSS Styles specified in one component do not override the rules in another component. Angular does this by using the View Encapsulation strategy.

In Angular for every component created or generated by the CLI, there is a specific style sheet for it. Angular was built in such a way that the styles defined inside the component style sheet are scoped to only that component no matter the class name. 

This is a lot like local and global variable definitions and how they are scoped; this scoping mechanism is known as encapsulation. Encapsulation is a very critical aspect of the modern web components standard which supports keeping every component modular and independent.

In Angular, a component's styles can be encapsulated within the component's host element so that they don't affect the rest of the application. The Component decorator provides the encapsulation option which can be used to control how the encapsulation is applied on a per component basis. This means that within your application you can have different components using different encapsulation strategies.

By default, Angular uses an emulated View Encapsulation to encapsulate CSS styles within their components so they can be isolated and only applied to the HTML elements within these components.

@Component({
  template: `<p>Using Emulator</p>`,
  styles: ['p { color:red}'],
  encapsulation: ViewEncapsulation.Emulated  
})

Q041. Why the isolated CSS is required per Angular Components?

Angular allows us the specify component-specific styles. This is done by specifying either inline-style styles or using the external style sheet styleUrls in the @Component decorator or @Directive decorator. 

The CSS Styles have a global scope. CSS rules apply to the entire document. You cannot apply rules to the part of the document. Hence, we use class, id & CSS specificity rules to ensure that the styles do not interfere with each other.

In Angular apps, the components co-exist with the other components. Hence it becomes very important to ensure that the CSS Styles specified in one component do not override the rules in another component. In web apps, CSS and styling are an essential part which means isolation and decoupling should also include CSS to prevent the styles from one feature, implemented as a module or component, to interfere with the styles of another feature.

There are many more reasons to isolate the CSS for every component. One of the important reasons is maintainability which is a crucial phase in any serious software or web development project. Component-based architectures, adopted by Angular and most modern frameworks nowadays including React and Vue, are about creating apps with isolated and decoupled components. 

Q042. What are the different View Encapsulation provided by Angular?

View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa. Angular provides three encapsulation strategies:

  1. Emulated (ViewEncapsulation.Emulated)
  2. ShadowDom (ViewEncapsulation.ShadowDom)
  3. None (ViewEncapsulation.None)

ViewEncapsulation.Native:  The viewEncapsulation Native has been deprecated since Angular version 6.0.8 and is replaced by viewEncapsulation ShadowDom.

Emulated is the default encapsulation method. Since this is the default Angular setting, without explicitly setting it up, it still does the same thing. 

You can change the default view encapsulation of a component via a decorator property called encapsulation. You first need to import ViewEncapsulation from the @angular/core package. Next, you add the encapsulation property to the component decorator and set its ViewEncapsulation property value to anything like ViewEncapsulation.None, ViewEncapsulation.ShadowDom, or ViewEncapsulation.Emulated.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})

Q043. What is Emulated ViewEncapsulation in Angular?

ViewEncapsulation.Emulated is the default encapsulation method in Angular. If you do not specify encapsulations in components, the angular uses the ViewEncapsulation.Emulated strategy by default.

The ViewEncapsulation.Emulated strategy in angular adds the unique HTML attributes to the component CSS styles and to the markup so as to achieve encapsulation like _ngcontent-c# attributes. This is not true encapsulation. The Angular Emulates the encapsulation, Hence the name Emulated.

In emulated encapsulation, Angular modifies the component's CSS selectors so that they are only applied to the component's view and do not affect other elements in the application, emulating Shadow DOM behavior. The styles of components are added to the <head> of the document, making them available throughout the application, but their selectors only affect elements within their respective components' templates.

Q044. What is ShadowDom ViewEncapsulation in Angular?

The ShadowDom achieves true encapsulation in Angular. It truly isolates the component from the styles of the other parts of the app.  Not all browsers support shadow DOMs yet, but Angular still implements the framework to achieve encapsulation by emulating the shadow DOM. Angular uses the browser's built-in Shadow DOM API to enclose the component's view inside a ShadowRoot, used as the component's host element, and apply the provided styles in an isolated manner.

The Shadow DOM is part of the modern Web Components standard that ensures encapsulation is carried out through its API, providing a way to attach a separated DOM to an element. So basically the shadow DOM allows you to hide DOM logic behind other elements without affecting any other part of the application so that you can use scoped styles in your component in isolation.

The Shadow DOM is a scoped sub-tree of the DOM. It is attached to an element (called shadow host) of the DOM tree. The shadow DOM does not appear as a child node of the shadow host when you traverse the main DOM.

The browser keeps the shadow DOM separate from the main DOM. The rendering of the shadow DOM and the main DOM happens separately. The browser flattens them together before displaying them to the user. The feature, state & style of the Shadow DOM stay private and are not affected by the main DOM. Hence it achieves true encapsulation.

The angular renders the component inside the #shadow root element. The styles from the component along with the styles from the parent and other components are also injected inside the shadow root. The styles of components are only added to the shadow DOM host, ensuring that they only affect elements within their respective components' views. To create shadow dom in angular, all we need to do is to add the ViewEncapsulation.ShadowDom as the encapsulation strategy.

Shadow Host: The app-shadowdom is the CSS selector in the ViewShadowdomComponent. The Angular renders the component as shadow dom and attaches it to the app-shadowdom selector. Hence, we call the element a Shadow host.

Shadow Root: The Shadow DOM starts from the #shadow-root element. Hence, we call this element a shadow root. The Angular injects the component into the shadow root. The Shadow boundary starts from the #shadow-root. The browser encapsulates everything inside this element including the node #shadow-root.

Q045. What is None ViewEncapsulation in Angular?

The None Encapsulation is used when we do not want any encapsulation. One of the options you have as an Angular developer is to specify that you do not want any kind of encapsulation of defined styles in your project. 

When you use this, the styles defined in one component affect the elements of the other components. So the style defined in the ViewNoneComponent will be injected into the global style (style.css) and override any previously defined style and it will reflect in the whole application. For example, the style p {color: blue;} overrides the style p {color: green;} defined in the styles.css.

So when you use None Encapsulation:
  • The styles defined in the component affect the other components
  • The global styles affect the element styles in the component

Here Angular does not apply any sort of view encapsulation meaning that any styles specified for the component are actually globally applied and can affect any HTML element present within the application. This mode is essentially the same as including the styles in the HTML itself.

The styles of components are added to the <head> of the document, making them available throughout the application, so are completely global and affect any matching elements within the document.

Q046. What is the difference between CSS vs. ngClass vs. ngStyle vs. style in Angular?

Angular provides built-in directives for dynamically applying CSS styles to components such as the ngClass and ngStyle directives. The ngClass directive can be used with the other class attributes as well.

Theoretically, they both are different at compile time, but practically the same at run time. The ngStyle is used to add style dynamically at run time. On the other hand, the ngClass is used to add some classes dynamically at run time but a class also holds some CSS content, so indirectly you are also adding CSS here dynamically.

The NgClass and NgStyle directives are used to apply a style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.

The "ng-style" and "ng-class" directives were used in AngularJs versions but now in the new Angular, we are using ngStyle and ngClass directives.

Style and Class:

When you need to apply dynamic styles to an HTML element using Angular, there are different options to consider. The first and most obvious solution is to use the regular style or class HTML attributes along with Angular data bindings:

<div [style.color]="errorTextColor">
   Invalid Email Id
 </div>

You can use the ternary operator as well in your expression to express a conditional styling:

<div [style.color]="hasError ? 'red': 'green' ">
   Invalid Email Id
</div>

The only problem is that if you want to apply multiple styles to the same element then it can get quite verbose because you need to use [style.property_name] for each and every style that you want. In that case, using a CSS class is a much better option. That’s where ngStyle comes into play.

NgClass:

The ngClass directive binds multiple CSS classes to the HTML element dynamically. It can assign or remove the class value to the element based on the condition. You can use either the expression or method with the ngClass directive.

In ng-class, you can bind a CSS class defined in some place, like Bootstrap. The ng-class directive translates your object into the class attribute.

<div [ngClass]="isGreen ? 'green':'blue'">Message</div>
<p [ngClass]="'selected'">Message</p>
<p ngClass="selected">Message</p>
<div [ngClass]="getClassValue()">Message</div>

NgStyle:

The ngStyle directive allows you to set the style property of the DOM Element dynamically. You can assign a style to the element like a string and you can also add conditions inside the string.

In ngStyle, you are setting the CSS style to any element. The ngStyle directive takes pairs of CSS properties and values.

<p [ngStyle]="{'color': 'white', 'font-size': '12px'}">Message</p>
<p [ngStyle]="{'color': 'white'}" style="margin: 5px;">Message</p>


There is one more use case for ngStyle. If you want to interpolate something in the style attribute, you should consider using ngStyle. 

For example instead of using style: style="width: {{progress}}"
You can use ngStyle: [ngStyle]="{'width':progress}"

Q047. What is NgClass Directive in Angular?

NgClass is an Angular Directive that allows us to conditionally apply one-to-many classes to an element. This provides a convenient way to work with multiple classes at once and apply them conditionally.

The native CSS class attributes apply one-to-many classes statically at compile time itself. But Angular’s class bindings allow only a single class to be conditionally applied at a time.

  • NgClass can take a String, Array of Strings, or Object Expression as input.
  • Under the hood, NgClass is adding/removing classes via Renderer2 addClass() and removeClass()
  • NgClass appends the class, it does not overwrite the existing one.

NgClass can receive input via inline declarations, or a property/method from our TypeScript class. So we can pass a Typescript property/method or even write an expression inline to our NgClass Directive. NgClass can take the following as input:

A space-delimited String: <div [ngClass]="is-info is-item has-border">Message</div>
An Array of Strings: <div [ngClass]="['is-info', 'is-item', 'has-border']">Message</div>
An Object: <div [ngClass]="{'is-info': true, 'is-item': true}">Message</div>

All of the above examples are inline but that could be replaced with a Typescript property or method as long as the expression returns valid input: 

<div [ngClass]="myStringProperty">Message</div>
<div [ngClass]="getClassValue()">Message</div>

Ternary Statements are also valid input, as long as they return a valid string, array, or object.

<div [ngClass]="isGreen ? 'green' : 'blue'">Message</div>

Q048. What is the NgStyle Directive in Angular?

In Angular ngStyle is a directive that allows us to conditionally apply one-to-many styles to an element. This provides a convenient way to work with multiple styles at once and apply them conditionally.

Native style attributes apply one-to-many styles statically at compile time itself. But Angular’s style bindings allow only a single style to be conditionally applied at a time.

NgClass and NgStyle share a significant amount of functionality and behavior. However, the key difference is:

NgStyle takes a key-value pair object, where the key is a CSS style. Similar to NgClass, NgStyle can be passed input inline or use a Typescript property/method

<div [ngStyle]="myObjectExpressionProperty">Message</div>

  • NgStyle accepts a key-value pair object as input, where the key is a valid CSS Style.
  • NgStyle can be passed as input via inline or a Typescript property or method.
  • NgStyle under the hood utilizes Angular’s Renderer2 to invoke setStyle() and removeStyle()
  • NgStyle applies styles and not classes.
  • NgStyle will overwrite styles defined by the native style attribute. So NgStyle will overwrite existing styles on the element if any.



Recommended Articles




Thanks for visiting this page. Please follow and join us on  LinkedInFacebookTelegramQuoraYouTubeTwitterInstagramWhatsApp, VKTumbler, and Pinterest for regular updates.

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.