Property Binding
- Property binding is used to bind values to the DOM properties of the HTML elements.
- Every HTML element is represented as a JavaScript DOM object and every attribute of the HTML element is represented as a DOM property.
- We can bind the DOM properties using the values in the component. The property to bound with the value can either be specified in square brackets [] or the property can be prefixed with bind-
Write the below code in app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: string = 'Welcome to Angular App Development';
isDisabled: boolean = false;
myText: string = "Hello World";
backgroundImgUrl: string ="https://www.xyz.com/images/logo-wide.png";
public color = 'red';
public size = '20px';
public fontStyle = 'italic';
}
Write the below code in app.component.html
<h1>{{"Property Binding"}}</h1> <br/>
<img [src]="backgroundImgUrl" style="height:40px"> <br/>
<div [innerHTML]="title"></div> <br/>
<input [value]='myText'> <br/>
<button [disabled]='isDisabled'>Click me</button> <br/>
<button bind-disabled ='true'>Click me</button>
<span [style.background]='color'>This span has red background</span>
<span [style.color]='color' [style.font-size]='size' [style.font-style]='fontStyle'>This span is red.</span>
Now if you run the code using ng serve
, you will see the output as shown below
References
- https://angular.io/guide/template-syntax#property-binding-property
We will discuss about Style and Class Binding in our upcoming Blog article.
Happy Learning!