Is it effectively no longer possible to use Angular directives as an "HTML decorator" as I've taken to calling them?
I found this pattern invaluable in Angular 1.x for migrating legacy applications to Single Page Apps by first building a set of directives that would add functionality to markup generated by the server. It seems like an oversight for the Angular Team to eliminate that functionality.
A Contrived Example:
There is a jQuery plugin for prettier select boxes called chosen. In 1.x I would do the following on a page that was returned from the server.
HTML:
<select chosen-select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
JS
app.directive('chosenSelect', [
function() {
return {
restrict: 'AE',
link: function(scope, element, attributes) {
$(element).chosen();
}
};
}
]);
This would execute the chosen plugin on the HTML generated by the server and I didn't need any real changes to my pages other than defining an ng-app. Can this style of directive no longer be done using Angular 2+?
Thanks
You can do the same:
import {Directive, ElementRef, OnInit} from '@angular/core';
declare var $: any;
@Directive({selector: '[promoChosenSelect]'})
export class ChosenSelectDirective implements OnInit{
constructor(private el: ElementRef) {
}
ngOnInit(): void {
$(this.el.nativeElement).chosen();
}
}
in module:
@NgModule({
imports: [],
exports: [
ChosenSelectDirective
],
declarations: [
ClickOutsideDirective,
],
entryComponents: [],
providers: []
})
export class SharedModule {
}
and here html:
<select promoChosenSelect>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.