HTML වලට අමතර ක්රියාකාරීත්වයක් එක් කරන Custom Directives, දත්ත සංදර්ශනය කරන ආකාරය වෙනස් කරන Pipes සහ Components සඳහා Styles යොදන ආකාරය පිළිබඳව මෙහිදී ඉගෙන ගනිමු.
Angular හි ඇති `*ngIf`, `*ngFor` වැනි built-in directives වලට අමතරව, අපටම directives නිර්මාණය කළ හැකිය. ප්රධාන වර්ග දෙකකි:
Element එකක පෙනුම හෝ හැසිරීම වෙනස් කරයි. උදාහරණයක් ලෙස, element එකක් මතට mouse එක ගෙන ආ විට එහි පසුබිම් වර්ණය වෙනස් කරන directive එකක් සෑදිය හැක.
Directive එකක් generate කිරීමට Angular CLI command එක: ng generate directive highlight
// highlight.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string | null) {
this.el.nativeElement.style.backgroundColor = color;
}
}
භාවිතා කරන ආකාරය:
<p appHighlight>Hover over me to highlight!</p>
DOM එකට elements එකතු කිරීමෙන් හෝ ඉවත් කිරීමෙන් HTML layout එක වෙනස් කරයි. මේවා නිර්මාණය කිරීම තරමක් සංකීර්ණ වන අතර සාමාන්යයෙන් Attribute Directives වලට වඩා අඩුවෙන් භාවිතා වේ.
Pipes යනු template HTML එක තුළ දත්ත සංදර්ශනයට පෙර ඒවායේ ආකෘතිය (format) වෙනස් කිරීමට භාවිතා කරන සරල functions වේ. Pipe එකක් භාවිතා කිරීමට | සලකුණ යොදයි.
Angular මගින් සපයන ලද pipes කිහිපයක්:
{{ 'hello' | uppercase }} → HELLO{{ 'WORLD' | lowercase }} → world{{ today | date:'shortDate' }}{{ 1234.56 | currency:'LKR' }} → LKR1,234.56{{ 0.75 | percent }} → 75%අපට අවශ්ය පරිදි අපගේම pipes නිර්මාණය කළ හැකිය. උදාහරණයක් ලෙස, දී ඇති අකුරු ගණනකට වඩා වැඩි text එකක් කෙටි කර "... " ලෙස පෙන්වන pipe එකක්.
Pipe එකක් generate කිරීමට CLI command එක: ng generate pipe summary
// summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'summary'
})
export class SummaryPipe implements PipeTransform {
transform(value: string, limit?: number): string {
if (!value) return null;
let actualLimit = (limit) ? limit : 50;
return value.substring(0, actualLimit) + '...';
}
}
භාවිතා කරන ආකාරය:
{{ longText | summary:20 }}
Angular components වලට styles යෙදීමට ක්රම කිහිපයක් ඇත.
සෑම component එකකටම තමන්ගේම CSS file එකක් ඇත (`.css`). මෙම file එකේ ඇති styles එම component එකට පමණක් සීමා වේ (encapsulated). වෙනත් components වලට බලපෑමක් ඇති නොකරයි. මෙය Angular හි ප්රබල ලක්ෂණයකි.
// user-profile.component.ts
@Component({
...
styleUrls: ['./user-profile.component.css']
})
/* user-profile.component.css */
h1 {
color: blue; /* This will only apply to h1 tags in UserProfileComponent's template */
}
`src/styles.css` ගොනුවේ යොදන styles, සම්පූර්ණ යෙදුමටම (application) පොදු වේ.
කොන්දේසි මත පදනම්ව class හෝ style එකක් යෙදීමට Property Binding භාවිතා කළ හැක.
<!-- Applies the 'active' class only if isActive is true -->
<div [class.active]="isActive">...</div>
<!-- Sets the font color to red only if hasError is true -->
<div [style.color]="hasError ? 'red' : 'black'">...</div>