6. Attribute binding
Attribute binding
Attribute binding is also a type of one way data binding.
In Angular few properties or Attributes are not treated as properties. Hence we can't use property binding and interpolation on such attributes. If we try to do so, that through compilation errors.
In Angular few properties or Attributes are not treated as properties. Hence we can't use property binding and interpolation on such attributes. If we try to do so, that through compilation errors.
Examples: colspan and rowspan.
when we try to use interpolation or property binding on the above attributes, there will be a compilation error as follows.
Uncaught Error: Template parse errors: Can't bind to 'colspan' since it isn't a known property
To avoid this type of problems we come across attribute binding. This attribute binding can be done along with either with interpolation or property binding.
Syntax: [attr.colspan]="value" or attr.rowspan="{{Value}}".
Here attr. will convert the attributes to accept interpolation or property binding.
By this way we can use attribute binding,
Example Program:
Create a sample component using following command
ng g c sample --skipTests (V8) or ng g c sample --spec=false (< v8).
The Above command creates there files as follows
1. sample.component.html 2. sample.component.ts 3. sample.component.scss.
Sample.component.html
<table> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr> <tr> <td>February</td> <td>$80</td> </tr> <tr> <td attr.colspan="{{colSpanValue}}">Sum: $180</td> </tr> </table>
sample.comonent.scss
table,tr,td { border: 1px solid black; }
sample.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-sample', templateUrl: './sample.component.html', styleUrls: ['./sample.component.scss'] }) export class SampleComponent { colSpanValue = 2; constructor() { } }
Comments
Post a Comment