You are on page 1of 34

1604C054 – Hybrid Mobile Programming

Angular Binding and


Angular Directive

Week 03
Program Studi Teknik Informatika
Fakultas Teknik – Universitas Surabaya
Angular Binding
What is Binding
Binding in the context of web development and frameworks like Angular
refers to the process of establishing a connection or relationship between
the data in your application (often stored in a component or model) and the
user interface (UI) elements in your application's templates or views.

The primary goal of binding is to ensure that changes in one part of your
application are reflected in another automatically, creating dynamic and
responsive user interfaces.
What is Binding (2)
Binding allows you to:

1.Display Data: You can display data from your application's data model (often JavaScript objects or
variables) in your HTML templates. For example, you can show the user's name or a product's price in a
web page.

2.Capture User Input: You can capture user input, such as form submissions, button clicks, or text input,
and use that input to update your application's data model or trigger actions in response to user
interactions.

3.Keep UI in Sync: When your data changes, either due to user input or other factors, the bound UI
elements automatically update to reflect those changes. Conversely, when a user interacts with the UI,
the data model is updated accordingly.
Interpolation Binding
= The simplest and most commonly used forms of data binding in Angular. It allows you to
display the value of a component property directly in your template.

Interpolation isn't limited to simple properties. You can also use expressions, such as
mathematical calculations or method calls, inside the curly braces.

.
Syntax: The basic syntax for interpolation is

{{ expression }}

where expression is a reference to a property or an expression in your component.


Interpolation Binding (2)
Example 1 : We will modify List page. We add caption that include today date.

in list.page.html add:
<ion-row>
<ion-title>
Product List per {{today}}
</ion-title>
</ion-row>

in list.page.ts add:
export class ListPage implements OnInit {

today:string='9 September 2023'

constructor() { }
Interpolation Binding (3)
Example 2 : We will try to call method/function.

in list.page.html modify:
Product List per {{today_ind()}}

in list.page.ts add function


today_ind():string
{
const currentDate = new Date();
// Get the current day (1-31)
const d = currentDate.getDate();
// Get the current month (0-11, where 0 is January and 11 is December)
const m = currentDate.getMonth() + 1; // Adding 1 to convert to 1-12 range
// Get the current year (four-digit year)
const y = currentDate.getFullYear();

return d+'-'+m+'-'+y;
}
Exercise 1 (max 15 minutes)
Can you change the month number with month name ?

Can you do it without if or switch ? (hint:use array)

Can you add day name before the date? (hint: getDay() )
Event Binding
Event binding in Angular allows you to listen for and respond to events (such as mouse
clicks, key presses, or custom events) that occur in your application's user interface. You
can use event binding to trigger functions or methods in your component class when
specific events happen.
Event binding in Angular uses parentheses () to bind to events in your HTML templates.
The syntax is as follows:

<element (event)="expression"></element>

example

<button (click)="onButtonClick()">Click Me</button>


Event Binding (2)
Example : We will add button to go to previous date listing.
When user click the button, it will change the currentDate with yesterday date.
Because we need to access current date in other function, we have to modify the
currentDate variable in today_ind() function as class property.

export class ListPage implements OnInit {


currentDate = new Date();

Class property need to access with "this" keyword.

today_ind():string
{
const d = this.currentDate.getDate();
const m = this.currentDate.getMonth() ;
const y = this.currentDate.getFullYear();
Event Binding (3)
Add a button with event binding that call goYesterday function in page.html

<ion-button (click)="goYesterday()">Previous Day</ion-button>

Add a function in page.ts :

goYesterday()
{
this.currentDate.setDate(this.currentDate.getDate() - 1);
}
Event Binding (4)
other event which can use in binding:
(mousedown) and (mouseup): These events capture mouse button presses and releases.
(mousemove): Captures mouse movement within an element.
(keydown) and (keyup): These events capture keyboard key presses and releases.
(focus) and (blur): These events are triggered when an element gains or loses focus, typically used with form
elements like input fields.
(submit): Captures form submission events.
(change): Triggered when the value of a form element (e.g., input, select) changes.
(input): Emits when the user interacts with an input element, such as typing or pasting text.
(mouseenter) and (mouseleave): These events trigger when the mouse enters or leaves an element.
(dragstart), (drag), and (dragend): These events are related to drag-and-drop operations.
(scroll): Captures scrolling events on scrollable elements.
(resize): Triggered when the browser window is resized.
(load) and (unload): These events are related to the loading and unloading of resources, such as images and pages.
Property Binding
Property binding is a fundamental concept in Angular that allows you to associate (or bind) a
property of an HTML element in your template with a property of a component. This binding
establishes a connection between the component's property and the DOM element's property,
enabling dynamic updates from the component to the DOM.

syntax:
[binding_target] ="binding_expression"

example:
<img [src]="imageUrl" alt="Image" />

• [src] is the binding target, representing the src property of the <img> element.
• "imageUrl" is the binding expression, referring to a property named imageUrl in your component.
Property Binding (2)
Example : We only have list of product data for 5 days before. Therefore, we will disabled Yesterday
button after it clicked 5 times.

Add in yesterday button :


<ion-button (click)="goYesterday()" [disabled]="is5daysago"

add in page.ts :
is5daysago=false
numberclicked=0
------
goYesterday()
{
this.currentDate.setDate(this.currentDate.getDate() - 1);
this.numberclicked++
if(this.numberclicked==5) this.is5daysago=true
}
Exercise 2 (max 10 minutes)
Can you Add Tomorrow Button ?
Tomorrow button will add 1 day after current day.
Tomorrow button is disable when the date is today. and enable when the day is
yesterday or longer.
Two way binding
Two-way data binding is a concept in Angular that allows you to establish a synchronization between a
property in your component class and an input element's value in your template. It enables changes made to
the input element in the template to automatically update the corresponding property in your component
class, and vice versa. Two-way binding simplifies the process of capturing and reflecting user input in real-
time.
In Angular, two-way data binding is typically achieved using the ngModel directive, which combines
property binding and event binding to create a seamless bidirectional data flow.

example:
<input [(ngModel)]="username" />

• [(ngModel)] is the two-way binding syntax.


• "username" is the component property (in the component class) that you want to bind to the input element's
value.
Text in Input element will be changed if username variable change.
there is variable in page.ts : conversely,
username variable value will be updated when user write any text in
username: string = '' input element.
Two way binding (2)
IMPORTANT!
Two way binding must import FormsModule from @angular/forms and add it to the imports
array of your Angular module .

Please check your list.module.ts .


The FormsModule import now is a default import when we generate page. Therefore we not need to add
anything here and we can directly use ngModel.
Two way binding (3)
Example
We will add a text input for user fill coupon code. The text input value will relate with couponcode class
property.
First, we set default value for the coupon code as, for example, '0000' this value will reflect in the text input
component. This is the binding from class property to input component.
Second, we will modify the text input value. It will reflect automatically in the couponcode variable. We will
add interpolation binding to check the value of couponcode variable. And this is proving the second binding,
from input component to class property.

Add couponcode variable in page.ts :

couponcode:string="0000"
strvalid:string="Invalid"
discount:number=0
Two way binding (4)
Add input text and interpolation binding for checking in page.html :

<ion-input label="Masukkan kode : " [(ngModel)]="couponcode"></ion-input>


Coupon code {{couponcode}} is {{strvalid}} you get {{discount}}% discount
Exercise 3 (max 15 minutes)
If (keyup) is an event binding after that raise after user press a character in
keyboard, can you put function checkValid that validate the couponcode in
hardcoded (next, it should check in the database) and change the respond text below:
If couponcode is '1234' the text shows :
Coupon code 1234 is valid. you get 5% discount.
If couponcode is '6789' the text shows :
Coupon code 6789 is valid. you get 10% discount.
Exercise 4 (max 5 minutes)
Use setting page. The Setting page will be use as setting out profile. It can store our
profile photo.

Can you link a text input and an image, when user put url of a photo in internet, this
url will be use in image src and will be shown directly.
Exercise 5 (max 20 minutes)
Still use setting page . The Setting page will also be for set up our password.

If checked is a property that define a checkbox is checked or not,


Can you create a Password strength checkers ?
What to be check is :
more than 6 characters
include number
include special character (!@#$%^&*)

Each checkbox above will be checked if user input is satisfied the related criteria
Angular Directives
ngStyle
The ngStyle directive in Angular allows you to dynamically apply inline CSS styles to
HTML elements based on expressions in your component. It's a powerful way to style
elements based on component data or conditions.

syntax example:

<div [ngStyle]="{ 'font-size.px': fontSize, 'color': textColor }">Styled Text</div>

fontSize and textColor is class properties


ngStyle (2)
Example:
We will set color of responded coupon code text ("Coupon code xxxx is yyyy") to
become red when the code is Invalid, and green when valid.

Add ngStyle in the text. Because it doesn't placed in any element, we have to put it in element,
like <div> or <span> or <p>
<span [ngStyle]="{'color': textcolor }">
Coupon code {{couponcode}} is {{strvalid}} ...
</span>

Add class properties:

textcolor:string="red"
Exercise 6 (max 5 minutes)
Modify your checkValid function in exercise 3, so it will set textcolor to red when
invalid and green when valid
*ngIf
The ngIf directive in Angular is a structural directive that allows you to conditionally
render or remove elements from the DOM (Document Object Model) based on the
evaluation of a provided expression. It's a fundamental directive for controlling the
visibility and existence of HTML elements in your templates.

syntax example:

<div *ngIf="isVisible">Cilukba<div>

=There is isVisible class property. If this isVisible variable is True, the div will appear and text
"Cilukba" will be visible, otherwise if isVisible variable is False the div will be not rendered and
user can not see "Cilukba" text.
*ngIf (2)
Example:
We will add congratulation animated gif image when the couponcode inputed by user is
valid.

Add in page.html :

<ion-img *ngIf="strvalid=='Valid'"
src="https://absen.titip.in/congratulation.gif"></ion-img>
*ngFor
The *ngFor directive in Angular is a structural directive used for iterating over a
collection, such as an array, and rendering HTML elements for each item in the
collection. It allows you to create repeated content dynamically in your templates.

syntax :
<div *ngFor="let item of items; let i = index">
<!-- Content to repeat for each item -->
</div>
let item of items:
let item is a local template variable that represents the current item in the iteration. You can name this variable whatever you like; in this case, it's
named item.
of items specifies the collection (array or iterable) over which you want to iterate. items is the name of the array or iterable in your component that
you want to loop through.
let i = index (Optional):
let i is an optional local variable that represents the current index of the item in the iteration.
= index assigns the index value to the i variable. You can use i to track the index of each item in the collection.
*ngFor (2)
Example:
We will show products data. Products is an array of objects. Objects here is still 'ugly', we
not define it in class or interface in order to shorten time.
products = [
{
name: "Laptop",
price: 999.99,
description: "A powerful laptop for work and gaming.",
},
{
name: "Smartphone",
price: 499.99,
description: "A high-end smartphone with advanced features.",
},
{
name: "Headphones",
price: 99.99,
description: "Over-ear headphones for immersive audio.",
},
];
*ngFor (3)
In page.html :

<ul>
<li *ngFor="let product of products">
<h2>{{ product.name }}</h2>
<p>Price: ${{ product.price }}</p>
<p>{{ product.description }}</p>
</li>
</ul>
Exercise 7 (max 15 minutes)
Add discount in every product object.
Show the discount after product name.
If there is discount, Strikeout the Price text
and add Price after discount below it.
Exercise 8 (max 15 minutes)
Apply more discount when user input the Valid couponcode.
Strikeout again the price with discount in the item, and add new price that apply discount
from item and discount from couponcode.
Question ?

You might also like