Linking data from a component.ts
file to the component.html
file is an
example of one-way binding. Changes made to the component.ts
file are
reflected in the view, but changes made in component.html
have no influence
on component.ts
. Information flows in one direction only.
As we saw in Angular lessons 1 and 2, the syntax for binding a variable is to
encase its name in double braces {{ }}
. We used this in the exercises and
studios to display headings, titles from our movie list, astronauts on our
crew, etc.
Example
Inside the my-list.component.ts
file:
1export class MyListComponent implements OnInit {
2 listHeading: string = 'My Great List';
3 luckyNumber: number = 42;
4
5 constructor() { }
6
7 ngOnInit() { }
8}
Inside the my-list.component.html
file:
<h3>{{listHeading}}</h3>
<p>{{luckyNumber}}<p>
Changing the value of luckyNumber
in the MyListComponent
class will
change the text displayed by the p
element. However, altering the HTML will
NOT affect the value of luckyNumber
in the class.
We also used one-way data binding to modify attributes within an HTML tag. For
example, assume the image
variable holds the URL for a photo we want to use
on our web page.
Example
Inside the photos.component.ts
file:
1export class PhotosComponent implements OnInit {
2 image: string = 'https://www.launchcode.org/assets/icons/trophy-95e8cbe9bfda44123422302951deb1c92a237d39052669b8fbfafec00cb4f608.png';
3
4 constructor() { }
5
6 ngOnInit() { }
7}
Inside the photos.component.html
file:
<img src="{{image}}"/>
Within the <img>
tag, we bind the image
variable to the src
attribute. Note that the braces and variable name must be inside quotes. When
the code runs, the string stored in image
is used to provide the required
URL.
Angular allows us to use an alternate syntax whenever we use data-binding to modify an HTML attribute.
To avoid cluttering up our HTML tags with lots of double braces {{ }}
, we
simplify the notation as follows:
Examples
Double braces syntax:
<img src="{{ variableName }}"/>
<input name="{{ otherVariable }}" value="{{ thirdVariable }}"/>
Alternate syntax:
<img [src]="variableName"/>
<input [name]="otherVariable" [value]="thirdVariable"/>
Instead of {{ }}
, place the HTML attribute in square brackets [ ]
and
set that equal to the variable name in quotes.
Note: Although the two methods accomplish exactly the same thing, the square brackets syntax is recommended as a best practice.
Question
Which of the following is NOT a true statement about data-binding?
Question
Which of the following show proper data-binding syntax? Choose ALL that apply.
<li>{{ variableName }}</li>
<img [src]="variableName"/>
<p>[variableName]</p>
<button value="[variableName]">Go!</button>
<input placeholder="{{ variableName }}"/>
<button [name]="{{ variableName }}"/>