Francis C. answered 08/06/24
Frontend Software Engineer with 25+ years of Experience
DOM manipulation is best performed by using a directive. This is true for the first version of AngularJs as well as for the modern Angular. Here is a quick example using the AngularJs version.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Directive Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.directive('changeBgOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function() {
element.css('background-color', attrs.changeBgOnClick);
});
}
};
});
</script>
</head>
<body>
<div change-bg-on-click="yellow">Click me to change my background color to yellow!</div>
</body>
</html>
If using the current version of Angular - here is the recommended approach.
import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';
@Directive({ selector: '[appChangeBgOnClick]' })
export class ChangeBgOnClickDirective {
@Input('appChangeBgOnClick') backgroundColor: string = ";
constructor(private el: ElementRef, private renderer: Renderer2) { }
@HostListener('click') onClick() {
this.changeBgColor(this.backgroundColor || 'yellow');
}
private changeBgColor(color: string) {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
}
}