Monday 10 February 2020

Angular 8 Session 10 - Attribute Binding In Angular

Attribute Binding


* Attribute Binding is another form of one-way data-binding in angular like interpolation and property binding we have which deals with html element attributes.
HTML Attributes vs DOM Properties
* Attributes are defined by HTML elements where properties get converted by DOM from those attributes.
* Angular always deals with element properties and events, not with attributes. Attribute is responsible for initialises DOM properties.
* As per our last example we saw we have been using the disabled attribute for data binding, but its logically not true as internally we are assigning the value to its properties.
<button [disabled]=‘isEnabled’>Click Me</button>

* Attributes value can’t be changed but DOM properties value can be changed. 
* To check in browser developer tool's console window make use of element's   id + . + value to get properties value to get attribute value element's id + . + getAttribute("value").

Attribute Binding
* There is one exception to rule that binding happens with element properties but in case    of attribute binding it only deals with element attributes.
* Usually property binding preferred to set an element’s property but in some cases there are some attributes doesn’t has the respective properties to bind like SVG, colspan, aria etc…
* It’s syntax is similar to property binding but instead of element property it resides with attr prefix followed by a dot (.) to name of element attribute.
<button [attr.aria-label]="actionName">{{actionName}} with Aria</button>

* Similarly, consider to set a colspan attribute using following approach.
<button [attr.aria-label]="actionName">{{actionName}} with Aria</button>

* There is one major difference between colspan & colSpan is colSpan is a property and can be binded with property binding as discussed in previous tutorial but colspan not able to perform same.
app.component.cs

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component2.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Angular8Demo';
  myData = "angular";
  isEnabled = false;
  colspan = 2;
}

app.component2.html

<div style="text-align: center;">
    <button [disabled]='isEnabled'>Click me</button>
    <input type="text" id="txtDemo" value="SKMDotNet" />
    <br /><br />
    <button [attr.aria-label]="myData">{{title}}</button>
    <br /><br />
    <table border="2">
        <thead>
            <tr>
                <td>First Name</td>
                <td>Last Name</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td [attr.colspan]="colspan">Sunil Kumar Malana</td>
            </tr>
        </tbody>
    </table>
</div>


No comments:

Post a Comment

Angular 8 Session 21 - ngFor Directive In Angular

ngFor Directive Content will be resume soon. Stay tuned!