Angular

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

One-way binding (HTML to component)

(target)='statement'

Give some examples of structural directives

*ngIf directive conditionally adds or removes an element from the dom based on the value of an expression *ngFor - used to loop over a collection of items and generate a series of elements for each item

What is angular universal

Angular Universal is a technology used for server-side rendering (SSR) of Angular applications. It allows developers to render their Angular applications on the server side and then send the pre-rendered HTML pages to the client instead of sending only the JavaScript bundle. This approach improves the initial load time of the application and enhances the search engine optimization (SEO) of the application.

modules

Angular applications are composed of one or more modules, which are containers that group related components, services, and other assets. Each module defines a cohesive set of functionality, and can be imported by other modules to form a larger application.

What is the design pattern supported by Angular?

Angular followed MVC design pattern, where M defines Model (Logic and request-response data model), V defines View (HTML, CSS, all kind of UI component) and C defines Controller (the connection between view & model).

Angular is a framework or library?

Angular is a framework, as it has all features in the build. Like a router, HTTP module for ajax call, browser animation, unit testing support with Jasmin Karma, and so on. Whereas React, Vue is a library as every respective task like routing, HTTP call, unit testing requires separate library support.

Directives

Directives are used to add behavior to existing HTML elements or create custom HTML elements. Angular comes with a set of built-in directives, such as ngIf and ngFor, and also allows developers to create custom directives.

Dependency Injection

In Angular, dependency injection is enforced by the framework itself. When you declare a dependency in a component's constructor, Angular takes care of providing an instance of the required service to the component at runtime. This is achieved through the Angular dependency injection (DI) system, which creates and manages a tree of injectors that provide instances of services to the components that require them. Injecting the services that a controller needs as arguments to the controller function Angular's dependency injection (DI) system is used to manage the creation and lifecycle of objects within an application. DI is used to provide services to components, which allows for greater modularity and testability.

mergeMap

In the context of Angular, mergeMap is commonly used in conjunction with HTTP requests to handle scenarios where multiple HTTP requests need to be made and their results combined into a single stream

Give an example of dependency injection with attribute directive

Lets say you wanted to create a custom directive that would highlight certain elements when they are clicked. So you create your directive using @directive and in the constructor you would inject the ElementRef depdendency service. This would provide access to the underlying DOM element that the directive is applied to. We could use this to toggle the highlight CSS class on the element import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) {} @HostListener('click') onClick() { this.el.nativeElement.classList.toggle('highlight'); } } <div appHighlight>Click me to highlight</div>

give an example of an attribute directive

Lets say you wanted to create a custom directive that would highlight certain elements when they are clicked. You could create an attribute directive called 'apphighlight' that applies a CSS class to the element when its clicked import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) {} @HostListener('click') onClick() { this.el.nativeElement.classList.toggle('highlight'); } } <div appHighlight>Click me to highlight</div>

structural directives how do you declare a structural directive? how are they different from attribute directives

Structural directives are a type of directive that can modify the structure of the DOM by adding, removing or manipulating elements. Structural directives are distinguished from attribute directives, which modify the behavior or appearance of existing elements by adding, removing, or manipulating ATTRIBUTES (like CSS styling, disabled, ngclass, ngStyle) structrual directives are denoted by a '*" symbol before the directive name. This syntax is used to indicate the directive is a structural directive and will modify the structure of the DOM

Elevator Pitch

Tech Lead and Software engineer with experience delivering full stack applications in an Agile environment driven by love of technology and passion for problem solving. Pioneered adoption and conversion efforts for 8 developers moving from a .NET Framework monolith tech stack to a microservices architecture using Angular (FE) and .NET Core/Sql Server (BE) under rigid time constraints. I have developed multiple microservices in .NET Core for vaulting and retrieving secrets and data lineage that leverages a Microsoft SQL Server database built to serve thousands of daily users. As a proven leader, I have spearheaded front-end design and implementation efforts on projects developed with Angular, HTML, and CSS, all built on .NET Core backends. I have brought two applications from pre-POC stage, to LLE infrastructure setup including CI/CD all the way to production deployment in less than a year. I am currently the lead developer on my team's Azure adoption for cloud based data governance and metadata management. I have established a fresh modern design for data synchonization that uses a low code, event based architecture to provide a more resilient and modern solution to the banks data movement requirements. I am now eager to tackle more complex challenges and elevate my engineering prowess by leveraging my expertise and broad exposure to many technologies.

Templates

Templates define the structure of the view associated with a component. Templates are written in HTML, and can include special Angular syntax for data binding, event handling, and other features.

ngStyle

The ngStyle directive allows you to set CSS style on an HTML element conditionally.

RxJS pluck operator

The pluck operator is commonly used in RxJS to extract specific properties from objects emitted by Observables, making it easy to work with complex data structures. It can also be used with multiple property names to extract values from nested objects, or with arrays to extract specific elements. const people$ = new Observable<object>(observer => { observer.next({ name: 'Alice', age: 25 }); observer.next({ name: 'Bob', age: 30 }); observer.next({ name: 'Charlie', age: 35 }); }); // Use the pluck operator to extract the "name" property value const names$ = people$.pipe( pluck('name') );

RxJS tap operator

The tap operator is commonly used in RxJS to perform side effects on an Observable, such as logging, updating state, or triggering other actions // Use the tap operator to log the emitted values const loggedNumbers$ = numbers$.pipe( tap(num => console.log(`Emitted: ${num}`)) );

What are RxJS transformation operators?

There are many RxJS operators used in the Angular ecosystem, the most common pipeable operators are map, tap, pluck, do, etc. But there are a few advanced operators are there like mergeMap, switchMap, concatMap, exhaustMap.

How do you pass data from one component to another component?

There are many ways data can be shared from one component to another component. If component A is a parent of component B - Data share from A to B using @Input decorator, data can be shared from component A to component B (Parent to Child) If component A is a parent of component B - Data share from B to A using @Output and event emitter data can be shared from component B to Component A (Child to Parent) If component A and component B does not have any parent-child relation 1. Use service variable to share data from A to B 2. can be created a shared service variable and access the data across applications by injecting share service. 3. Use Subject or BehaviroulSubject to send data using Observer way. 4. Can create a Singleton class with the setter & getter method, and access the data across applications. 5. If the application is too large, the NGRX store can be used to share data as well. (Not recommended for small scale application)

@injectible decorator What additional configuration object does it accept?

Used to declare a class as a provider that can be injected as a dependency into other classes or components It accepts a configuration object that can include a 'providedIn' property that defines the scope of use for the service. @Injectable({ providedIn: 'root' }) export class MyService { constructor(private http: HttpClient) {} getSomeData() { return this.http.get('/api/some-data'); } }

What is decorator (metadata) in Angular? give some example -

What is decorator (metadata) in Angular? give some example - A. Decorator that marks a class as an Angular component and provides configuration metadata that determines how the component should be processed, instantiated, and used at runtime. The metadata represents by the decorator. Example: @Component, @Directive, @Input, @Output, @ViewChild, @HostListner, @HostBinding and so on.

describe using an observer from a route guard

When an observable is returned from a route guard, the navigation is NOT blocked. instead, the observable emits values that can be used to allow or deny access to the route. observables are better suited for scenarios where the guard needs to make multiple asynchronous calls to retrieve data because they offer more advanced features and greater flexibility for handling asynchronous data streams example, the UI needs to make a call to get the users profile (auth) first and then make a call to get the users permissions (authz) so observables are better suited for this

How can you improve the changeDetection's efficiency? what use cases make sense for this?

You can use the OnPush changeDetection. You would need to specify this in the components decorator explicitly. This would be useful if your component has a large number of properties or if the data changes frequently so that the performance is not determined.

two-way binding (component to HTML to component)

[(target)]='expression'

two way binding

a combination of property binding and event binding. it allows you bind a component property to an input element and update the value of the property whenever the user changes the value in the input element. You use square brackets and parenthesis together with the ngMODEL directive to implement two way binding. <input [(ngModel)]="username"> In this example, the username property in the component is bound to the value of the input element, and changes to the input element are automatically reflected in the username property of the component.

Singleton class

a design pattern that restricts the instantiation of a class to a single instance and provides global access to that instance. You would make the constructor a private class so its not accessible.

What are directives?

a fundamental building block of angular applications that allow you to extend and customize HTML syntax. Directives are essentially markers on a DOM element (such as an attribute, element name, or CSS class) that tells Angulars compiler to attach a specified behavior to that element

How do promises work?

a promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It is a way to handle asynchronous operations such as fetching data from an API or executing an expensive computation without blocking the main thread. A promise has three possible states: Pending: The initial state of a promise when it is created. Fulfilled: The state of a promise when it successfully completes its operation and returns a value. Rejected: The state of a promise when it fails to complete its operation and throws an error. Promises have two main methods: then(): This method is used to handle the fulfilled state of a promise. It takes two arguments: a callback function that will be called with the value returned by the promise, and an optional callback function that will be called if the promise is rejected. catch(): This method is used to handle the rejected state of a promise. It takes one argument: a callback function that will be called with the error message thrown by the promise.

What is resolver service in angular and why do we need them?

a resolver service is a service that pre-fetches data for a component before the component is actually loaded. It helps to ensure that the data required by a component is available before the component is displayed to the user. Resolver services are used to handle situations where a component needs data from an API or a remote server before it can be displayed. If the data is not pre-fetched, the component may be displayed with an empty or incomplete view until the data is loaded, which can lead to a poor user experience. Resolver services are implemented as Angular services, and can be added to the routing configuration for a particular route. When the route is activated, the resolver service will be called to fetch the data required by the component before the component is displayed.

what is a decorator

a special kind of function that can be used to modify the classes, methods, properties and parameters. They provide powerful features like dependency injection, metadata annotation, and component, and directive decoration. In typescript, decorators are denoted by an @ symbol, followed by the name of the decorator function. Decorators can be applied to classes, methods, properties, and parameters by placing them immediately before the declaration.

interpolation

a type of data binding. used to display the value of a component property in the view. You use double curly braces to interpolate a component property in the view

What is the auxiliary route? and when do need them with an example?

an auxiliary route is a secondary route that can be defined for a component along with the primary route. It is also known as a named router outlet. In the router file, a property of outlet would be defined const routes: Routes = [ { path: 'products', component: ProductListComponent }, { path: 'products/:id', component: ProductDetailComponent, outlet: 'sidebar' }, ]; An auxiliary route is useful when we want to display multiple components in a single view, each with its own URL. For example, suppose we have an e-commerce application with a product list view and a product detail view. We may want to display the product detail view as a side-by-side panel alongside the product list view, rather than navigating to a separate page. Here, the ProductDetailComponent is defined as an auxiliary route with the named outlet sidebar. We can then use the routerLink directive to navigate to the auxiliary route in our template, like this: <a [routerLink]="['/products', { outlets: { sidebar: ['products', product.id] } }]">View Details</a>

attribute directives, what decorator do you use

attribute directive is a type of directive that can modify behavior or appearance of an element by adding, removing, or manipulating attributes on that element. When you create an attribute directive, you use the @directive decorator to define the directives metadata, including its selector (which identifies the attribute the directive will be applied to), and any associated behavior (implemented as methods and properties on the directive class).

What are some key differences between observables and promises/callbacks

callbacks/promises are both one-time events, meaning they are triggered once when an asynchronous operation completed. Observables conversely are streams of data that can emit multiple events over time. You have many more options as to how you can manage the incoming data

What are the different types of directives

component directive attribute directive structural directive

event binding

event binding is used to respond to user events in the view, such as a button click or a mouseover event. You use parentheses '()' to bind a component method to an event in the view <button (click)="doSomething()">Click me</button> In this example, the doSomething() method in the component is called when the user clicks the button element.

what are the 4 types of data binding in angular

interpolation property binding event binding two way binding

NGRX store

is a state management library for Angular applications that provides a centralized store to manage state and data flow in a predictable, immutable way. It is based on the principles of the Redux architecture pattern and provides a single source of truth for the application state. The NGRX Store library provides a Store object that holds the current state of the application, as well as a set of reducers that define how the state should be updated in response to actions. Actions are simple objects that describe a change to the state, and they are dispatched to the Store using the dispatch method. Selectors are another important feature of the NGRX Store library. Selectors are functions that extract a specific piece of data from the application state, and they can be used to provide computed values and derived data to the application components

What are the main components of angular

modules components templates services directives dependency injection

What attribute directive allows you to create two way data binding between form control and a variable in your component

ngModel <input type="text" [(ngModel)]="name">

Difference between a constructor and ngOnInit

ngOnInit is a lifecycle hook in angular. ngOnInit is used to perform more complex initialization logic that depends on injected services. The constructor is called when the component is instantiated, and ngOnInit is called after the component's properties have been initialized and all injected services have been resolved. constructor should be used for basic initialization of component properties. example: import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-data-component', template: '<p>{{ data }}</p>' }) export class DataComponent implements OnInit { data: string; constructor(private dataService: DataService) {} ngOnInit(): void { this.dataService.getData().subscribe((data) => { console.log('Data received from service:', data); this.data = 'Processed data: ' + data; console.log('Data processed by component:', this.data); }); } } the constructor initalizaes the injected data service. the ngOnInit is then used to do complex initialization of data using the injected service

What is lazy loading and how is it typically implemented

only load necessary parts of your application at runtime. using the loadChildren property of the routerModule

what is concapMap and what uses them

operator is used to sequentially concatenate multiple observables into a single observable stream. It takes a source observable and a function that returns an observable, and it subscribes to the observables returned by the function in sequence, waiting for each one to complete before subscribing to the next one. This can be useful for scenarios where you want to ensure that asynchronous operations are executed in a specific order. For example, in the context of a wizard or multi-step form, you might want to execute asynchronous validation or data loading operations in a specific order.

class decorators

p

observables

represent a stream of data that can be observed and acted upon in various ways. they provide a way to handle asynchronous and even driven data streams in a more declarative way than traditional callback approaches For example, when making HTTP requests or retrieving data from a database, the response or data can be returned as an observable. Components can then subscribe to the observable to receive the data when it is available, rather than relying on callbacks or other asynchronous techniques.

property binding

sets the value of an HTML element property to the value of a component property You use square brackets '[]' to bind a component property to an HTML element property

Give a use case for a component directive

suppose you want to create a custom button component that can be reused throughout your application

what is swtichMap and what uses them? give a real world use case of this

switchMap is used to flatten nested observables into a single observable stream. this subscribes to a function returning observables and will toggle or SWITCH its stream to a new observable every time a new one comes. It takes a source observable and a function that returns an observable, and it subscribes to the observable returned by the function. When a new value is emitted by the source observable, the previous subscription is cancelled and a new subscription is created to the new observable. This can be useful for scenarios where you want to cancel previous asynchronous operations when a new one is triggered. For example, in the context of an autocomplete search, you might want to cancel previous searches when a new search term is entered.

What is a template

the HTML markup that defines the components appearance

selector property

the selector property is used to define how a component directive can be referenced in an HTML template. the selector property takes a string value that represents the name of the component, and this name is used as the HTML tag for the component in the template @Component({ selector: 'app-tooltip', // ... }) export class TooltipComponent { // ... } <app-tooltip></app-tooltip>

How do you retrieve necessary data before a route is activated? this would ensure user does not see protected content momentarily while the route guard is processing

use the resolve feature. it allows you to resolve a promise before the route is activated and inject the resolved data into the component associated with the route

what are route guards

used to control access to routes based on certain conditions. they are implemented as classes that implement the 'canActivate' interface and return a boolean, promise or observable

What is mergeMap and what uses them

used to merge multiple observables into a single observable stream. It takes a source observable and a function that returns an observable, and it subscribes to all the observables returned by the function. When a new value is emitted by the source observable, a new subscription is created to the new observable. This can be useful for scenarios where you want to combine the results of multiple asynchronous operations into a single stream. For example, in the context of a search with multiple data sources, you might want to merge the results of searches from multiple sources into a single stream.

RxJS map operator

used to transform values emitted by an observable into new values. It takes a function as an argument, which is applied to each emitted value, and returns a new Observable that emits the transformed data

How do you make an Observable work Synchronously?

using await and async and returning the observable as a Promise (using .toPromise())

describe using a promise for a route guard

whne a promise is returned from a route guard, the navigation is blocked until the promise is resolved or rejected. This means the user will see a blank screen until the promise is resolved or rejected. promises are better suited for scenarios where the guard needs to make a single astrnchronous call to retrieve some data

How to lazy load a table in angular

you can use the *ngIf directive so that the table will only display if the data has been loaded You must also use the @viewChild in the component as well view <table #mytable *ngIf="tableLoaded"> <!-- Table code here --> </table> component @ViewChild('myTable') myTable: any;

One-way binding (component to HTML):

{{ object_expression }} OR [target]='object_expression'

How do you call multiple APIs (non-dependent) at the same time?

RxJS forkJoin operator to make multiple HTTP requests in parallel. forkJoin is used to combine the results of multiple observables into a single observable that emits an array of values in the same order as the input observables.

What is RxJS, and why do we need it?

RxJS is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. The library also provides utility functions for creating and working with observables. These utility functions can be used for: Converting existing code for async operations into observables Iterating through the values in a stream Mapping values to different types Filtering streams Composing multiple streams

Services

Services are used to encapsulate reusable functionality that can be shared across components. Services can provide data access, caching, authentication, or any other functionality that can be used by multiple components.

component directive and how do you create one in angular

A type of directive that defines a new component, which is a self contained UI element that encapsulates its own HTML template and associated behavior. When you create a component directive, use the @component decorator to define the components metadata, including its selector(the name youll use to reference it in your HTML template), its template (the hTML markup that defines the components appearance), and any associated behavior (implemented as methods and properties on the component side)

How do you call REST API from your Angular application?

A. To call REST API, we need to import HTTPClientModule in the application module. Also, we need to inject HTTPClient to call GET, PUT, POST, DELETE based on API signature.

ngIf

Adds or removes an element from the DOM based on a condition.

Attribute directive

Allows you to modify the behavior or appearance of an existing element by adding custom behavior to it through the use of an HTML attribute. Angular attribute directives are added to HTML elements as attributes, and they can modify behavior or appearance or both. They can be used to add, remove or modify an elements attributes, classes, styles or event listeners. Attribute directives can have input binding to allow users to pass data to the directive, and they can have output binding to allow the directive to emit events.

What are Angular life Cycle hooks? give some examples.

Angular lifecycle hooks are a set of methods that are called at specific points during the lifecycle of an Angular component or directive. These hooks allow developers to write code that responds to changes in the component or directive, and to perform tasks such as initializing component data, handling user events, and cleaning up resources when a component is destroyed. Here are some examples of Angular lifecycle hooks: ngOnInit(): This is called once after the component is initialized and all its inputs have been bound. This is a good place to perform one-time initialization tasks such as retrieving data from a server. ngOnChanges(): This is called when one or more of the component's input properties change. This hook provides information about the changes that occurred, such as the previous and current values of the input properties. ngOnDestroy(): This is called just before the component is destroyed. This is a good place to perform cleanup tasks such as unsubscribing from observables or releasing resources. ngAfterViewInit(): This is called once after the component's view has been initialized. This is a good place to perform initialization tasks that require access to the component's view, such as setting up event handlers. ngDoCheck(): This is called during every change detection cycle, which can be triggered by a variety of events such as user input or data changes. This hook allows developers to perform custom change detection logic.

NgClass

Attribute directive that adds or removes CSS classes from an element based on a condition Example: <button [ngClass]="{'active': isActive, 'disabled': isDisabled}">Click me!</button> Active and disabled classes will be implemented in the CSS file. When the button element has the active class, it will be green and when it is disabled it will be grey and the cursor will not be allowed.

What is changeDetection?

Change Detection means updating the DOM whenever data is changed. In its default strategy, Angular will run the change detector to update the DOM whenever any data is mutated or changed. ChangeDetection can happen with the following scenario - @Input value has changed A DOM event that the component is listening to was triggered An AsyncPipe received a new value Change detection has been explicitly triggered (detectChanges, markForCheck)

components

Components are the building blocks of an Angular application. Each component defines a view, which is a section of the user interface, and associated behavior. Components can contain other components, and can interact with the application's services to retrieve and manipulate data.

What is the current version of Angular?

Currently, angular version 15 has been released. 16 in may

What is data binding? is it possible to have one-way and two-way binding from view to the source?

Data binding means - a component object is interpolated with an HTML template, so the object value can be displayed in HTML. yes it is

Pipe method and what library is it from

RXJS, the method can be used on an Observable object The pipe method is being used to combine multiple operators The pipe method is used in the example above to allow for potential future expansion of the method's functionality with additional operators. Even if there is currently only one operator being used (map), the developer may have added the pipe method in anticipation of adding more operators later on. Using the pipe method allows for a cleaner and more modular implementation of the code, making it easier to add, remove or modify operators as needed without having to change the structure of the method.


Kaugnay na mga set ng pag-aaral

Properties of Multiplication and Addition

View Set

Chapter 8. Styling with Fonts and Colors: Expanding Your Vocabulary

View Set

Social Psychology Chapter 9 Review

View Set

ANSC 107 - Male & Female Reproductive Systems Quiz

View Set

Chemistry: 2.3 - Dalton's Atomic Theory

View Set

MGT 4230 Chapter 15 - Global Production and Supply Chain Management

View Set