You are on page 1of 15

Unit -2

1) A) What is databinding? Explain the Interpolation binding with examples.

Ans:

Data binding deals with how to bind your data from component to HTML DOM elements
(Templates). We can easily interact with application without worrying about how to insert
your data. We can make connections in two different ways one way and two-way binding.
Before moving to this topic, let’s create a component in Angular 8.
Open command prompt and create new Angular application using below command −
cd /go/to/workspace
ng new databind-app
cd databind-app
Create a test component using Angular CLI as mentioned below −
ng generate component test
The above create a new component and the output is as follows −
CREATE src/app/test/test.component.scss (0 bytes) CREATE
src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614
bytes)
CREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545
bytes)
Run the application using below command −
ng serve

One-way data binding

One-way data binding is a one-way interaction between component and its template. If you
perform any changes in your component, then it will reflect the HTML elements. It supports
the following types −

String interpolation

In general, String interpolation is the process of formatting or manipulating strings. In


Angular, Interpolation is used to display data from component to view (DOM). It is
denoted by the expression of {{ }} and also known as mustache syntax.
Let’s create a simple string property in component and bind the data to view.
Add the below code in test.component.ts file as follows −
export class TestComponent implements OnInit {
appName = "My first app in Angular 8";
}

Move to test.component.html file and add the below code −


<h1>{{appName}}</h1>
Add the test component in your app.component.html file by replacing the existing content
as follows −
<app-test></app-test>
Finally, start your application (if not done already) using the below command −
ng serve
You could see the following output on your screen −

1) B) What is 2-way data binding? Explain 2-way data binding with ngmodel with
suitable example?

Ans)

Two-way data binding

Two-way data binding is a two-way interaction, data flows in both ways (from component
to views and views to component). Simple example is ngModel. If you do any changes in
your property (or model) then, it reflects in your view and vice versa. It is the combination
of property and event binding.

NgModel

NgModel is a standalone directive. ngModel directive binds form control to property and


property to form control. The syntax of ngModel is as follows −
<HTML [(ngModel)]="model.name" />
For example,
<input type="text" [(ngModel)]="model.name" />
Let’s try to use ngModel in our test application.
Configure FormsModule in AppModule (src/app/app.module.ts)

import { FormsModule } from '@angular/forms'; @NgModule({


imports: [
BrowserModule,
FormsModule
]
})
export class AppModule { }
FormModule do the necessary setup to enable two-way data binding.
Update TestComponent view (test.component.html) as mentioned below −
<input type="text" [(ngModel)]="userName" />
<p>Two way binding! Hello {{ userName }}!</p>
Here,
Property is bind to form control ngModeldirective and if you enter any text in the textbox, it
will bind to the property. After running your application, you could see the below changes −
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −

Now, try to change the input value to Jack. As you type, the text below the input gets
changed and the final output will be as shown below −
Question 2)
A) Illustrate about template interpolation with an example.

Ans)

Interpolation and template expressions

Interpolation allows you to incorporate calculated strings into the text between HTML
element tags and within attribute assignments. Template expressions are what you use to
calculate those strings.

Interpolation {{...}}

Interpolation refers to embedding expressions into marked up text. By default, interpolation


uses as its delimiter the double curly braces, {{ and }}.

In the following snippet, {{ currentCustomer }} is an example of interpolation.


src/app/app.component.html

content_copy<h3>Current customer: {{ currentCustomer }}</h3>

The text between the braces is often the name of a component property. Angular replaces that
name with the string value of the corresponding component property.
src/app/app.component.html

content_copy<p>{{title}}</p>

<div><img src="{{itemImageUrl}}"></div>
In the example above, Angular evaluates the title and itemImageUrl properties and fills in the
blanks, first displaying some title text and then an image.

More generally, the text between the braces is a template expression that Angular
first evaluates and then converts to a string. The following interpolation illustrates the point
by adding two numbers:
src/app/app.component.html

content_copy<!-- "The sum of 1 + 1 is 2" -->

<p>The sum of 1 + 1 is {{1 + 1}}.</p>

The expression can invoke methods of the host component such as getVal() in the following
example:
src/app/app.component.html

content_copy<!-- "The sum of 1 + 1 is not 4" -->

<p>The sum of 1 + 1 is not {{1 + 1 + getVal()}}.</p>

Angular evaluates all expressions in double curly braces, converts the expression results to
strings, and links them with neighboring literal strings. Finally, it assigns this composite
interpolated result to an element or directive property.

You appear to be inserting the result between element tags and assigning it to attributes.
However, interpolation is a special syntax that Angular converts into a property binding.
If you'd like to use something other than {{ and }}, you can configure the interpolation
delimiter via the interpolation option in the Component metadata.
Template expressions

A template expression produces a value and appears within the double curly braces, {{ }}.
Angular executes the expression and assigns it to a property of a binding target; the target
could be an HTML element, a component, or a directive.

The interpolation braces in {{1 + 1}} surround the template expression 1 + 1. In the property
binding, a template expression appears in quotes to the right of the = symbol as
in [property]="expression".

In terms of syntax, template expressions are similar to JavaScript. Many JavaScript


expressions are legal template expressions, with a few exceptions.

You can't use JavaScript expressions that have or promote side effects, including:

 Assignments (=, +=, -=, ...)
 Operators such as new, typeof, instanceof, etc.
 Chaining expressions with ; or ,
 The increment and decrement operators ++ and --
 Some of the ES2015+ operators
Expression context

The expression context is typically the component instance. In the following snippets,


the recommended within double curly braces and the itemImageUrl2 in quotes refer to
properties of the AppComponent.
src/app/app.component.html

content_copy<h4>{{recommended}}</h4>

<img [src]="itemImageUrl2">

An expression may also refer to properties of the template's context such as a template input


variable,

let customer, or a template reference variable, #customerInput.


src/app/app.component.html (template input variable)

content_copy<ul>

<li *ngFor="let customer of customers">{{customer.name}}</li>

</ul>

src/app/app.component.html (template reference variable)

content_copy<label>Type something:

<input #customerInput>{{customerInput.value}}

</label>

The context for terms in an expression is a blend of the template variables, the


directive's context object (if it has one), and the component's members. If you reference a
name that belongs to more than one of these namespaces, the template variable name takes
precedence, followed by a name in the directive's context, and, lastly, the component's
member names.

2) B) What is the use of “ngfor”? illustrate with an example.

Ans)

ngFor Directive

The *ngFor directive is used to repeat a portion of HTML template once per each item from
an iterable list (Collection). The ngFor is an Angular structural directive and is similar to
ngRepeat in AngularJS. Some local variables like Index, First, Last, odd and even are
exported by *ngFor directive.

Syntax of ngFor

See the simplified syntax for the ngFor directive:


1. <li *ngFor="let item of items;"> .... </li>  

ngFor Directive

To Use ngFor directive, you have to create a block of HTML elements, which can display a
single item of the items collection. After that you can use the ngFor directive to tell angular to
repeat that block of HTML elements for each item in the list.

Example for *ngFor Directive

First, you have to create an angular Application. After that open the app.component.ts and
add the following code.

The following Code contains a list of Top 3 movies in a movies array. Let's build a template
to display these movies in a tabular form.

1. import { Component } from '@angular/core';  
2. @Component({  
3.     selector: 'movie-app',  
4.     templateUrl:'./app/app.component.html',  
5.     styleUrls:['./app/app.component.css']  
6. })  
7. export class AppComponent   
8. {   
9.     title: string ="Top 10 Movies" ;  
10.     movies: Movie[] =[  
11.         {title:'Zootopia',director:'Byron Howard, Rich Moore',cast:'Idris Elba, Ginnifer G
oodwin, Jason Bateman',releaseDate:'March 4, 2016'},  
12.         {title:'Batman v Superman: Dawn of Justice',director:'Zack Snyder',cast:'Ben Aff
leck, Henry Cavill, Amy Adams',releaseDate:'March 25, 2016'},  
13.         {title:'Captain America: Civil War',director:'Anthony Russo, Joe Russo',cast:'Sca
rlett Johansson, Elizabeth Olsen, Chris Evans',releaseDate:'May 6, 2016'},  
14.         {title:'X-Men: Apocalypse',director:'Bryan Singer',cast:'Jennifer Lawrence, Olivi
a Munn, Oscar Isaac',releaseDate:'May 27, 2016'},  
15.     ]  
16. }   
17. class Movie {  
18.     title : string;  
19.     director : string;  
20.     cast : string;  
21.     releaseDate : string;  
22. }  

Now, open the app. component.html and add the following code:

1. <div class='panel panel-primary'>  
2.     <div class='panel-heading'>  
3.         {{title}}  
4.     </div>   
5.     <div class='panel-body'>  
6.         <div class='table-responsive'>  
7.             <table class='table'>  
8.                 <thead>  
9.                     <tr>  
10.                         <th>Title</th>  
11.                         <th>Director</th>  
12.                         <th>Cast</th>  
13.                         <th>Release Date</th>  
14.                     </tr>  
15.                 </thead>  
16.                 <tbody>  
17.                     <tr *ngFor="let movie of movies;">  
18.                         <td>{{movie.title}}</td>  
19.                         <td>{{movie.director}}</td>  
20.                         <td>{{movie.cast}}</td>  
21.                         <td>{{movie.releaseDate}}</td>  
22.                     </tr>  
23.                 </tbody>  
24.             </table>  
25.         </div>  
26.     </div>  
27. </div>  

3) A) How to pass value from HTML to file in angular? Explain with

Ans)

A component is considered as a ‘view’ with its own logic and data. Data binding is the
process of combining data values with their corresponding representations. For components,
string values can be passed, either directly as string literals or by storing the string literal in a
variable. There are 3 ways of passing string values to components in angular2. String value
bindings are described in the template section of the component.

Passing a string value to a component from its class: Here, the message variable will get its
value either from the constructor of the class or by using angular event bindings(user inputs).

Syntax:

<component>{{message}}</component>

Example:
It is the simplest way of passing a string to a component. The component ‘AppComponent’
has a selector called ‘app-display’ and the template for display is directed to
‘app.component.html’. When the class of the component contains the string data, it can be
accessed by the component by interpolation of the ‘content’ variable.

app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-display',
template: `app.component.html`
})

export class AppComponent {


content : string = "Hello World";
}

app.component.html

<p>Lendi</p>
<app-display> {{content}} </app-display>
Output:
Lendi
Hello World

3) B) How to create multiple modules? Explain with example.

Using multiple modules in Angular?

Using multiple modules is highly recommended as it gives you multiple advantages over a
single module architecture. If you are creating a sophisticated system which may be
extensively used it can help optimize the application while also helping you in a better source
code management. Before quickly moving towards the solution lets look at few benefits of
using multiple modules:

 Helps you organize your source code in ‘packages’


 Its possible to lazy-load modules, so that only modules which are being used right
now are loaded and others loaded on-demand. This can be achieved by module
routing as you will see below.
 You can reuse the same module in multiple applications for eg, a login module can be
reused between various enterprise applications using same auth provider and
mechanism.
Creating New Module

Creating new module is pretty easy and a single CLI job.

1ng generate module module_name


 If you want to use routing, you can enable by default by using the following:

1ng generate module module_name --routing=true


 All set of options can be figured out here in Angular ng CLI documentation.
 Creating components in the module
 When a new module is created using ng CLI, a new folder is created with the module
name and a module_name.module.ts file is generated inside that. All new components
that you want to add to the module should ideally be inside the same folder. For
creating a new component you can use the following CLI command.

1ng generate component component_name --module module_name


 Doing this will automatically import the component definition in the module.ts file
and you are good to go. By now your module.ts file should look something like the
following given that the module name is HomeModule and sample component name
is MainMenuComponent:

1 import { NgModule } from '@angular/core';


2 import { CommonModule } from '@angular/common';
3 import { MainMenuComponent } from './main-menu/main-menu.component';
4  
5 @NgModule({
6   declarations: [MainMenuComponent],
7   imports: [
8     CommonModule
9   ]
10 })
11 export class HomeModule { }

Reuse Components

One of the primary goal of using the modules is re-usability within and outside the current
project. To do that, the components which needs to be reused needs to be exported from the
module’s module.ts file and imported (yes, just like you import third party modules) to the
place where you wish to import.
This is how you export a component:

1 import { NgModule } from '@angular/core';


2 import { CommonModule } from '@angular/common';
3 import { MainMenuComponent } from './main-menu/main-menu.component';
4 import { RouterModule } from "@angular/router";
5  
6 @NgModule({
7   declarations: [MainMenuComponent],
8   imports: [
9     CommonModule
10   ],
11   exports: [
12     MainMenuComponent
13   ]
14 })
15 export class HomeModule { }
And similarly, the place where you would like to use it, you will need to import the module
as shown below:

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


2 import { NgModule } from '@angular/core';
3  
4 import { AppRoutingModule } from './app-routing.module';
5 import { AppComponent } from './app.component';
6 import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
7  
8 import { HomeModule } from "./modules/home/home.module"
9 import { CoreModule } from "./core/core.module";
10  
11 @NgModule({
12   declarations: [
13     AppComponent
14   ],
15   imports: [
16     BrowserModule,
17     AppRoutingModule,
18     BrowserAnimationsModule,
19     HomeModule,
20     CoreModule
21   ],
22   providers: [],
23   bootstrap: [AppComponent]
24 })
25 export class AppModule { }
Its a blessing to be able to re-use your components so easily. I personally have created my
own visualization libraries which I love to use in my private projects. You will find them
soon up for grab and source code released on GitHub. Now comes the last part, its routing!
Question 4)
A) Describe the Conditional Statement ngif with an example?

Ans)

NgIf is nice and simple, we simply can declare it on an element, or component, and let it
work its magic.

Placing the ngIf directive on a component, or element, will in fact hide or show that element
based on the expression you pass it to be evaluated.

Angular will simply add or remove your DOM nodes, mount or remount your components as
the expression changes (if it ever does, that’s up to you).

We’ll also cover why we use the asterisk syntax, shortly.

Standard *ngIf in Angular


There are four main ways we can use ngIf, so let’s start by exploring the most basic use case.

Let’s take an empty component and a simple Boolean value of true:

@Component({
selector: 'app-component',
template: `
<div>
Welcome back!
</div>
`,
})
export class AppComponent {
isLoggedIn = true;
}
We can also use JavaScript-like expressions to achieve a final truthy/falsy value to supply to
ngIf - as well as composing through multiple variables through various operators.

The basic syntax of the ngIf directive is simple and effective, all we need to do is prefix the
directive name with an asterisk (*) and add it anywhere inside our template:

<!-- negated variable to achieve "if not" -->


<div *ngIf="!isLoggedIn">
Please login, friend.
</div>

<!-- logic && operator -->


<div *ngIf="isLoggedIn && !isNewUser">
Welcome back, friend.
</div>

<!-- logic OR operator -->


<div *ngIf="isLoggedIn || isNewUser">
Welcome!
</div>
Just a few examples, but I’m sure you can see how easy and clean it is to use ngIf. Note that
the ngIf used is a lowercase “n” when declared on an element or component.

4) B) Contrast ngOnInit and constructor()?

Constructor: Constructor is the default method for a class that is created when a class is
installed and ensures the proper execution of the roles in the class and its subsections.
Angular are preferably the Dependency Injector (DI), analyzes the builder’s components and
when creating a new feature by calling the new MyClass() tries to find suppliers that match
the builder’s parameter types, resolve them and pass them to similar components.

ngOnInit: OnInit is a life cycle widget called Angular to show that Angular is made to create
a component. We have to import OnInit like this to use it (actually using OnInit is not
mandatory but it is considered good).

Difference between ngOnInit and Constructor:

 We mostly use ngOnInit in every startup/announcement and avoid things to work in


builders. The constructor should only be used to start class members but should not do
the actual “work”.
 So you should use the constructor() to set Dependency Injection and not much.
ngOnInit() is a better “starting point” – this is where / when component combinations
are solved.
 We use constructor() for all the initialization/declaration.
 It’s better to avoid writing actual work in the constructor.
 The constructor() should only be used to initialize class members but shouldn’t do
actual “work”.
 So we should use constructor() to set up Dependency Injection, Initialization of class
fields, etc.
 ngOnInit() is a better place to write “actual work code” that we need to execute as
soon as the class is instantiated.
 Like loading data from Database — to show the user in your HTML template view.
Such code should be written in ngOnInit().

Question
5) A) How to pass inputs and variables to components?

Passing Data into a Component


There are two ways to pass data into a component, with 'property binding' and 'event binding'.
In Angular, data and event change detection happens top-down from parent to children.
However for Angular events we can use the DOM event mental model where events flow
bottom-up from child to parent. So, Angular events can be treated like regular HTML DOM
based events when it comes to cancellable event propagation.
The @Input() decorator defines a set of parameters that can be passed down from the
component's parent. For example, we can modify the HelloComponent component so that
name can be provided by the parent.
import { Component, Input } from "@angular/core";
@Component({
selector: "rio-hello",
template: "<p>Hello, {{name}}!</p>",
})
export class HelloComponent {
@Input() name: string;
}
The point of making components is not only encapsulation, but also reusability. Inputs allow
us to configure a particular instance of a component.
We can now use our component like so:
<!-- To bind to a raw string -->
<rio-hello name="World"></rio-hello>
<!-- To bind to a variable in the parent scope -->
<rio-hello [name]="helloName"></rio-hello>

5) B) What is meant by Directive ? Explain types of directives in angular ?

Ans)
Attribute Directives
Attribute directives enable Angular developers to define an attribute that when added to an
element change the appearance of the element or enhance the functionality of the element.

Some examples of attribute directives include: - Highlighting the text of an element -


Focusing on an input when a specific action occurs - Showing a definition for a word when
the user hovers or clicks on an element - Hiding and showing a modal when a button is
clicked

Attribute directives have access to the ElementRef of the element where the attribute has
been applied. Using the ElementRef instance we can get access to the nativeElement in the
DOM. Keep in mind that Angular does not always execute within the context of a browser, so
be sure to check if the nativeElement is defined.

Structural Directives

Structural directives enable Angular developers to add, edit and remove elements in the
DOM. A good example of this is the built-in ngFor directive. Structural directives all begin
with an asterisk to denote that the directive modifies the structure of the DOM.

Note that when adding and removing elements using structural directives
like NgFor and NgIf that the DOM is indeed mutated. What I mean by this is that when an
element is removed it not simply hidden, it is actually removed from the DOM. The impact of
this is important to understand. If you remove an element that is a directive or contains
multiple directives, the directives are torn down and destroyed. Conversely, when you add an
element that contains one or more directives they are created and initialized at runtime.

Component (Directives)

Often time we refer to component directives simple as "components".

Components are special directives because they contain a template that is rendered in your
application. This enables you to define directives that contain templates using a rich HTML-
like syntax. This takes directives a step further in that you are not just modifying the DOM
via APIs, rather, you are inserting HTML directly into the DOM.

You might also like