ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Property Binding in Angular

In this guide let us explore the Property Binding in Angular with examples. Property binding is one way from component to view. It lets you set a property of an element in the view to property in the component. You can set the properties such as class,href,src,textContent, etc using property binding. You can also use it to set the properties of custom components or directives (properties decorated with @Input).

Property Binding Syntax

The Property Binding uses the following Syntax

                              

 
[binding-target]=”binding-source”
                            
                        

The binding-target (or target property) is enclosed in a square bracket []. It should match the name of the property of the enclosing element.

Binding-source is enclosed in quotes and we assign it to the binding-target. The Binding source must be a template expression. It can be property in the component, method in component, a template reference variable or an expression containing all of them.

Whenever the value of Binding-source changes, the view is updated by the Angular.

Property Binding Example

Create a new application

                              

ng new property
                            
                        

Open app.component.html

                              

<h1 [innerText]="title"></h1>
<h2>Example 1</h2>
<button [disabled]="isDisabled">I am disabled</button>

Open the app.component.ts

                              
 
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title="Angular Property Binding Example"
  
  //Example 1
  isDisabled= true;
 
}
                            
                        

We have two property binding in the example above

The title property of the component class is bound to the innerText property of the h tag.Disabled Property of the button is bound to the isDisabled Property of the component

Whenever we modify the title or isDisabled is the component, the Angular automatically updates the view.

Property Binding is one way

Property binding is one way as values go from the component to the template. When the component values change, the Angular updates the view. But if the values changes in the view, the Angular does not update the component.

Should not change the state of the app

The Angular evaluates the template expression (binding-source) to read the values from the component. It then populates the view. If the expression changes any of the component values, then the view would be inconsistent with the model. Hence we need to avoid using expression which will alter the component state.

It means that you cannot make use of the following

  • Assignments (=, +=, -=, …)
  • Keywords like new, typeof, instanceof, etc
  • Chaining expressions with ; or ,
  • The increment and decrement operators ++ and --
  • bitwise operators such as | and &
  • Return the proper type

    The binding expression should return the correct type. The type that the target property expects. Otherwise, it will not work

    Property_name_in_camel_case

    There are few element property names in the camel case, while their corresponding attributes are not. For example rowSpan & colSpan properties of the table are in the camel case. The HTML attributes are all lowercase (rowspan & colspan)

    Remember the brackets

    The brackets,[], tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the expression as a constant string and initializes the target property with that string:

    Content Security

    Angular inspects the template expression for untrusted values and sanitizes them if found any. For example, the following component variable evilText contains the script tag. This is what we call the script injection attack.The Angular does not allow HTML with script tags. It treats the entire content as string and displays as it is.

                                  
    
    Component
     
    evilText = 'Template <script>alert("You are hacked")</script> Syntax';
     
    Template
     
    <p [textContent]="evilText"></p> 
                                
                            

    DOM Properties, not attributes

    The property binding binds to the properties of DOM elements, components, and directives and not to HTML attributes. The angular has a special syntax for attribute binding.

    Special Binding

    The Angular has a special syntax for class, styles & attribute binding

    The classes & styles are special because they contain a list of classes or styles. The bindings need to be more flexible in managing them. Hence we have a class & style binding.

    The Property bindings cover all the properties, but there are certain HTML attributes that do not have any corresponding HTML property. Hence we have attribute binding

    Class binding

    You can set the class in the following ways. Click on the links to find out more

  • ClassName Property binding
  • Set the Class attribute with class binding
  • ngClass directive
  • Style Binding

    Similar to the class, the style also can be set using the following ways. Click on the links to find out more

  • Style Property Binding
  • ngStyle directive
  • Attribute Binding

    Sometimes there is no HTML element property to bind to. The examples are aria (accessibility) Attributes & SVG. In such cases, you can make use of attribute binding

    The attribute syntax starts with attr followed by a dot and then the name of the attribute as shown below

                                  
    
    
    //Template
     
    //Setting aria label
    <button [attr.aria-label]="closeLabel" (onclick)="closeMe()">X</button>
     
    //Table colspan
    <table border="1">
      <tr>
        <td>Col 1</td>
        <td>Col 2</td>
        <td>Col 3</td>
      </tr>
      <tr>
          <td [attr.colspan]="2">Col 1 & 2</td> 
          <td>Col 3</td>
      </tr>
      <tr>
          <td>Col 1</td>
          <td bind-attr.colspan = "getColspan()">Col 2 & 3 </td>
      </tr>
      <tr>
          <td>Col 1</td>
          <td>Col 2</td>
          <td>Col 3</td>
        </tr>
      
    </table>
     
                                
                            
                                  
    
    //Component
     
    closeLabel="close";
    getColspan() {
       return "2"
    }
                                
                            

    Property Binding Vs Interpolation

    Everything that can be done from interpolation can also be done using the Property binding. Interpolation is actually a shorthand for binding to the textContent property of an element.

    For example the following interpolation

                                  
    
    
     
    <h1> {{ title }} </h1>
                                
                            

    Is same as the following Property binding

                                  
     
    <h1 [innerText]="title"></h1>
     
                                
                            

    In fact, Angular automatically translates interpolations into the corresponding property bindings before rendering the view.

    Interpolation is simple and readable. For example, the above example of setting the h1 tag, the in interpolation is intuitive and readable than the property binding syntax

    Interpolation requires the expression to return a string. If you want to set an element property to a non-string data value, you must use property binding.

    Property Binding Example

    Binding to innerHTML with HTML tags

    Here the Angular parses the b & p tags and renders it in the view.

                                  
    <body>
    <app-root></app-root>
    </body>
                                
                            
                                  
    
    //Component
     text1="The <b>Angular</b> is printed in bold"
    text2="<p>This is first para</p><p>This is second para</p>"
                                
                            
    img
                                  
    
    //Template
     
    <img [src]="itemImageUrl">
    <img bind-src="itemImageUrl">
                                
                            
                                  
    
    //Component
    itemImageUrl="https://angular.io/assets/images/logos/angular/logo-nav@2x.png"
                                
                            
    Concatenate two string
                                  
    
    <p [innerText]="'Hello & Welcome to '+ ' Angular Data binding '"></p>
                                
                            
    Mathematical expressions
                                  
    
    
     <p [innerText]="100*80"></p>
                                
                            
    setting the color
                                  
    
    //template
    <p [style.color]="color">This is red</p>
                                
                            
                                  
    
    //Component
    color='red'