Property binding in Angular enables you to set values for properties of HTML elements, Angular components and more.
Use property binding to dynamically set values for properties and attributes. You can do things such as toggle button features, set image paths programmatically, and share values between components.
In this activity, you'll learn how to use property binding in templates.
To bind to an element's attribute, wrap the attribute name in square brackets. Here's an example:
<img alt="photo" [src]="imageURL">
In this example, the value of the src
attribute will be bound to the class property imageURL
. Whatever value imageURL
has will be set as the src
attribute of the img
tag.
-
Add a property called
isEditable
Update the code in
app.component.ts
by adding a property to theAppComponent
class calledisEditable
with the initial value set totrue
.export class AppComponent { isEditable = true;}
-
Bind to
contentEditable
Next, bind the
contentEditable
attribute of thediv
to theisEditable
property by using the[]
syntax.@Component({ ... template: `<div [contentEditable]="isEditable"></div>`,})
The div is now editable. Nice work 👍
Property binding is one of Angular's many powerful features. If you'd like to learn more checkout the Angular documentation.