Professional Documents
Culture Documents
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 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
1) B) What is 2-way data binding? Explain 2-way data binding with ngmodel with
suitable example?
Ans)
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
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 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 {{...}}
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
The expression can invoke methods of the host component such as getVal() in the following
example:
src/app/app.component.html
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".
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
content_copy<h4>{{recommended}}</h4>
<img [src]="itemImageUrl2">
content_copy<ul>
</ul>
content_copy<label>Type something:
<input #customerInput>{{customerInput.value}}
</label>
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
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.
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>
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`
})
app.component.html
<p>Lendi</p>
<app-display> {{content}} </app-display>
Output:
Lendi
Hello World
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:
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:
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).
@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:
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).
Question
5) A) How to pass inputs and variables to components?
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.
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)
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.