Tech Point Fundamentals

Saturday, February 17, 2024

Angular Interview Questions and Answers - Part 22

Angular Interview Questions and Answers - Part 22

Angular-Interview-Questions-And-Answers

Angular is a popular single-page application design framework and development platform. It is a robust open-source JavaScript framework that is widely used for front-end application development. Nowadays Angular is very famous as a frontend technology so it is important from 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 22nd part of the Angular Interview Questions and Answer series.

I will highly recommend that you 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:

Q246. How do you get the current route in Angular?
Q247. What is the safe navigation operator in Angular? 
Q248. What is the non-null assertion operator in Angular? How it is different from a safe navigation operator?
Q249. What does mean by relative path in Angular? How can you specify a relative route in Angular?
Q250. What is the child route in angular? How it is different from Nesting routes? 
Q251. What is the page title? How can you set the page title in Angular?
Q252. What is the Link Parameters Array in Angular?
Q253. What are the default LocationStrategy and URL styles supported by Angular?
Q254. What is the purpose of <base href> tag in Angular?
Q255. What do you understand by the RouterState?

Angular Interview Questions and Answers: Part 22


Q246. How do you get the current route in Angular?

There are different ways to get the current route in angular. You can get the URL property in both ActivatedRoute and Router service.

In Angular, there is a URL property of the router package to get the current route. In Angular, you can get the current route by injecting the ActivatedRoute service into your component and subscribing to its URL property. However, you can also get the same by using the Router service as well.

When the route changes, the URL property emits a new value, which can be accessed in the subscription callback. Import the Router from @angular/router and then Inject the router inside the constructor.

import { ActivatedRoute, Router} from '@angular/router';

export class ActivatedRouteDemoComponent {
  constructor(private route: ActivatedRoute, private router: Router) {
       console.log('Current URL: ' + this.router.url);    
  }

  ngOnInit() {
    this.route.paramMap.subscribe(url => {
      console.log('Current URL: ' + url );
    });
}

You can get the current route by accessing the router.url property. But If you are navigating the routes with Hash location strategy, the router.url will always return “/”. So it’s advisable to listen to the NavigationEnd event of the router to get the current route URL in Angular.

import { Router, NavigationEnd  } from '@angular/router';

constructor(private router: Router) {       
    this.router.events.subscribe((event) => {      
    event instanceof NavigationEnd ? console.log('Currunt URL: ' + event.url): null    
  })
}

Q247. What is the safe navigation operator in Angular?

In Angular safe navigation operator (?), guards against null and undefined values in property paths. The safe navigation operator is represented by the ?. symbol and is used to access the properties of an object without causing an error if the object is null or undefined

With the safe navigation operator, ?, the Angular framework stops evaluating the expression when it hits the first null value and renders the view without any errors.

The safe navigation operator in Angular is a feature that allows you to guard against null and undefined values in property paths when you are not aware of whether a path exists or not. It is also known as the Elvis Operator.

If there is no safe navigation operator and nullItem is null, JavaScript and Angular would throw a null reference error and break the rendering process of Angular: TypeError: Cannot read property 'name' of null.

<p>The user name is: {{user?.name}}</p>

Here, it protects against a view render failure if the user is null. If the user object is null, the view still renders but the displayed value is blank; you see only "The user name is:" with nothing after it.

Sometimes, however, null values in the property path may be OK under certain circumstances, especially when the value starts out null but the data arrives eventually.  The safe navigation operator works perfectly with long property paths such as a?.b?.c?.d.

Q248. What is the non-null assertion operator in Angular? How it is different from a safe navigation operator?

The non-null assertion operator (!) in Angular is a TypeScript feature that allows developers to assert that a value is not null or undefined. It is represented by the exclamation mark (!) and is used to suppress the “Object is possibly "null" or "undefined" error that occurs when TypeScript cannot determine if a value is null or undefined.

It is important to note that the non-null assertion operator should only be used when you are certain that a value is not null or undefined. If there is any doubt, it is better to use optional chaining or null coalescing instead.

    <p>The item's color is: {{item.color!.toUpperCase()}}</p>

When the Angular compiler turns your template into TypeScript code, it prevents TypeScript from reporting that item.color might be null or undefined.

As of Typescript 2.0, you can enforce strict null checking with the --strictNullChecks flag. TypeScript then ensures that no variable is unintentionally null or undefined. In this mode, typed variables disallow null and undefined by default. The type checker throws an error if you leave a variable unassigned or try to assign null or undefined to a variable whose type disallows null and undefined.

The type checker also throws an error if it can't determine whether a variable will be null or undefined at runtime. You tell the type checker not to throw an error by applying the postfix non-null assertion operator.

Unlike the safe navigation operator, the non-null assertion operator does not guard against null or undefined. Rather, it tells the TypeScript type checker to suspend strict null checks for a specific property expression. The non-null assertion operator, !, is optional with the exception that you must use it when you turn on strict null checks.

Q249. What does mean by relative path in Angular? How can you specify a relative route in Angular?

In Angular, a relative path is a path that is relative to the current URL segment. It is used to define paths that are relative to the current component’s route. Relative paths let you define paths that are relative to the current URL segment. The path: ' ' means to use the initial relative URL (' ').

In Angular, relative paths are used to import modules and components that are located in the same or sibling directory as the current file. Relative paths are specified using the" ./" and "../" syntax. The "./" syntax is used to specify the current directory, while the "../" syntax is used to specify the parent directory.

For example, if you are currently at the URL /products, and you want to navigate to the URL /products/details, you can use a relative path of details to navigate to the details route relative to the current URL segment.

For example, if you have a component located in the same directory as the current file, you can import it using a relative path like this:

import { MyComponent } from './my-component';

If you have a component located in a sibling directory, you can import it using a relative path like this:

import { MyComponent } from '../my-sibling-directory/my-component';

To specify a relative route in Angular, you can use the relativeTo property of the NavigationExtras object. This property specifies the route that the relative path is relative to. In the component class, import NavigationExtras from the @angular/router.

For example, if you want to navigate to the details route relative to the current URL segment, you can use the following code:

import { Router} from '@angular/router';

export class ActivatedRouteDemoComponent {
constructor(private router: Router) {    
}
goToDetails() {
    this.router.navigate(['details'], { relativeTo: this.route });
  }
}

Relative paths can be useful for organizing your application’s code into smaller, more manageable modules and components. However, as your application grows larger, relative paths can become cumbersome and difficult to maintain. In such cases, it may be better to use absolute paths or a module loader like SystemJS.

Q250. What is the child route in angular? How it is different from Nesting routes? 

In Angular, a child route is a route that is nested inside another route. It is used to define routes that are relative to the current component’s route. Child routes are useful when you want to create a hierarchical navigation structure in your application.

As your application grows more complex, you might want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you're adding a second <router-outlet> to your app because it is in addition to the <router-outlet> in AppComponent.

A child route is like any other route, in that it needs both a path and a component. The one difference is that you place child routes in a children array within the parent route. You can also define multiple child routes inside a parent route.

To define a child route in Angular, you need to specify the parent route and the child route in your routing configuration. The child route is defined as an array of routes inside the parent route.

const routes: Routes = [
  { path: 'parent', component: ParentComponent,
    children: [
      { path: 'child1', component: Child1Component },
      { path: 'child2', component: Child2Component }
  ]
  }
];

In this example, there are two additional child components, child-1, and child-2.

  <h2>Parent Component</h2>
  <nav>
    <ul>
    <li><a routerLink="child-a">Child 1</a></li>
    <li><a routerLink="child-b">Child 2</a></li>
    </ul>
  </nav>
  <router-outlet></router-outlet>

Q251. What is the Page Title? How can you set the page title in Angular?

Each page in your application should have a unique title so that it can be identified in the browser history. The Router sets the document's title using the title property from the Route config.

In Angular, the page title is the text that appears on the browser tab for a particular page. It is an important aspect of web development as it helps users identify the purpose of the page and search engines to index it properly.

const routes: Routes = [
  {
  path: 'product-component',
  title: 'Product',
  component: ProductComponent,
  children: [
    {
    path: 'home-product',  
    title: resolvedChildTitle,
    component: HomeProduct,  
    },
    {
    path: 'service-product',
    title: 'service-product',
    component: ServiceProduct,  
    },
  ],
  },
];
const resolvedChildTitle: ResolveFn<string> = () => Promise.resolve('home-product');

The title property follows the same rules as static route data and dynamic values that implement ResolveFn<>. You can also provide a custom title strategy by extending the TitleStrategy.

To set the page title dynamically in Angular, you can use the Title service provided by @angular/platform-browser. Here are the steps to set the page title:

  • Import the Title service in your component
  • Inject the Title service in your component’s constructor
  • Use the setTitle() method of the Title service to set the page title

You can set the page title dynamically by passing a string variable to the setTitle() method.

import { Title } from '@angular/platform-browser';

constructor(private titleService: Title) { }

let pageTitle = 'Tech Point Fundamentals';
this.titleService.setTitle(pageTitle);

Q252. What is the Link Parameters Array in Angular?

In Angular, a link parameters array is an array of values that are used to construct a URL for a particular route. It is used to pass data between components and to navigate to different routes in your application. A link parameters array holds the following ingredients for router navigation:

  • The path of the route to the destination component
  • Required and optional route parameters that go into the route URL

To create a link parameters array in Angular, you can use the routerLink directive in your HTML template. The routerLink directive accepts an array of values that represent the route you want to navigate to. You can bind the RouterLink directive to such an array like this:

  <a [routerLink]="['/products', productId]">View Product</a>

In this example, the routerLink directive is used to create a link to the /products route with a parameter of productId. When the user clicks on the link, the productId value is passed to the product component, which can then be used to display the appropriate product details.

You can also pass additional parameters to a route by including them in the link parameters array.

 <a [routerLink]="['/products', productId, { color: 'red', size: 'large' }]">View Product</a>

In this example, the color and size parameters are passed to the product component along with the productId parameter.

Q253. What are the default LocationStrategy and URL styles supported by Angular?

When the router navigates to a new component view, it updates the browser's location and history with a URL for that view. Modern HTML5 browsers support history.pushState, a technique that changes a browser's location and history without triggering a server page request. The router can compose a "natural" URL that is indistinguishable from one that would otherwise require a page load.

For example in the "HTML5 pushState" style: localhost:3002/product-details

However, Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" (called the "hash"). Routers can take advantage of this exception by composing in-application route URLs with hashes.

localhost:3002/src/#/product-details

LocationStrategy Providers in Angular:

The Angular router supports both location strategy styles with two LocationStrategy providers:

PathLocationStrategy: The default "HTML5 pushState" style.
HashLocationStrategy: The "hash URL" style.

In Angular, the default LocationStrategy is PathLocationStrategy. This strategy uses the HTML5 history API to manipulate the browser’s URL and history. It allows you to use normal-looking URLs without the hash symbol (#).

The other LocationStrategy supported by Angular is HashLocationStrategy. This strategy uses the hash symbol (#) in the URL to manipulate the browser’s history. It is useful for older browsers that do not support the HTML5 history API. Use HashLocationStrategy by providing the useHash: true in an object as the second argument of the RouterModule.forRoot() in the AppModule.

@NgModule({
  imports: [
  BrowserModule,
  FormsModule,
  RouterModule.forRoot(routes, { useHash: true })  
  ]
})

To use PathLocationStrategy, you need to add a <base href> element to your index.html file. This element specifies the base URL for all relative URLs in your application.

The RouterModule.forRoot() function sets the LocationStrategy to the PathLocationStrategy, which makes it the default strategy. You also have the option of switching to the HashLocationStrategy with an override during the bootstrapping process.

You must choose a routing strategy early in the development of your project because once the application is in production, visitors to your site use and depend on application URL references. Almost all Angular projects should use the default HTML5 style. It produces URLs that are easier for users to understand and it preserves the option to do server-side rendering.

Q254. What is the purpose of <base href> tag in Angular?

In Angular, the <base href> tag is used to specify the base URL for all relative URLs in your application. It is an important element for generating correct routes, especially when you are deploying your project in a subfolder.

The href attribute is used to specify the base URL for all relative URLs on a page. During navigation, the base href tag is used by the Angular router as a base path to the component, template, and module files.

The base href element has the Angular router to compose the navigation URLs. It tells the browser where actually the script files will execute and it helps the router to compose a navigation URL. A relative base URL helps in indexing better on the website server or on the working local website copy. 

By default, the value is set to "/" i.e root which means the scripts are in root the directory. The base href is mentioned in the index.html file within the <head></head> tags. This guide works with a CLI-generated Angular application. 

If you are working manually, make sure that you have <base href="/"> in the <head> of your index.html file. However, if your application is deployed at https://techpointfunda.com/prod/, you would set the base href tag to <base href="/prod/">. This ensures that all relative URLs in your application are resolved relative to the /prod/ path.

The routing application should add an element to the index.html as the first child in the tag to indicate how to compose navigation URLs. If the app folder is the application root then you can set the href value as below:

<head>
  <meta charset="utf-8">
  <title>TechPoint</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

When you use the Angular router to navigate between different views and components in your application, it uses the base href tag to compose the navigation URLs. Without that tag, the browser might not be able to load resources (images, CSS, scripts) when "deep linking" into the application. 

If you do not set the base href tag, the Angular router will use the current URL as the base URL for all relative URLs in your application. This can cause issues if your application is deployed in a subdirectory or if you are using a server-side rendering solution.

You must add a <base href> element to the application's index.html for pushState routing to work. The browser uses the <base href> value to prefix relative URLs when referencing CSS files, scripts, and images.

Q255. What do you understand by the RouterState?

In Angular, the RouterState is a tree of activated routes that represents the state of the router as it keeps changing over time when users navigate from page to page.  Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. It is an immutable data structure that contains the current state of the router, including the current URL, the current route, and any route parameters or query parameters.

The RouterState is created by the Angular router and is updated every time the user navigates to a new route. It is used by the router to determine which components to display on the screen and how to arrange them.

You can access the RouterState in your Angular application by injecting the ActivatedRoute service into your component. The ActivatedRoute service provides access to the current route’s state, including the RouterState.

The router state in Angular represents the current state of the Angular router. It contains information about the current route, including the URL, route parameters, query parameters, and other related data. The router state can be accessed and manipulated using the Angular Router service. It provides a way to programmatically navigate, retrieve information about the current route, and handle route changes in Angular applications.

You can access the current routerState from anywhere in the application using the Router service and the routerState property.

import { RouterState } from '@angular/router';

@Component({templateUrl:'index.html'})
  class MyComponent {
    constructor(router: Router) {
    const state: RouterState = router.routerState;
    const root: ActivatedRoute = state.root;
    const child = root.firstChild;
    const id: Observable<string> = child.params.map(p => p.id);
    }
  }





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.