I've been able to upgrade an angularjs element directive to be used in angular 4. Here's a sample code:
[myScores.js]
angular.module('app.components.directives.myScores', [])
.directive('myScores', function() {
return {
scope: {
score: '=',
},
template: '<div>>>> Your score is {{score}} <<<',
link: function(scope) {
console.log("in myScores", scope)
}
};
});
[myScores.ts]
import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';
@Directive({
selector: 'my-scores'
})
export class MyScoresDirective extends UpgradeComponent {
@Input() score: number;
constructor(elementRef: ElementRef, injector: Injector) {
super('myScores', elementRef, injector);
}
}
Notice I'm using UpgradeComponent to upgrade the myScores element directive. I've tried the same on an attribute directive but got an error. Is there a way to upgrade an attribute directive?
Here's my attempt of upgrading an attribute directive:
[makeGreen.js]
angular.module('app.components.directives.makeGreen', [])
.directive('makeGreen', function() {
return {
restrict: 'A',
link: function(scope, element) {
console.log("in makeGreen", scope)
console.log("element", element)
element.css('color', 'green');
}
};
});
[makeGreen.ts]
import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';
@Directive({
selector: '[makeGreen]'
})
export class MakeGreenDirective extends UpgradeComponent {
@Input() count: number;
@Output() clicked: EventEmitter<number>;
constructor(elementRef: ElementRef, injector: Injector) {
console.log("elementRef", elementRef.nativeElement)
super('makeGreen', elementRef, injector);
}
}
I get an error when loading a page that has something like:
<div makeGreen>Text should be green</div>
I got this error:
Error: Directive 'makeGreen' is not a component, it is missing template.
A Attribute directive can totally have the Input property which can be passed to it from the tag where it's used : For ex:
Also make sure your appModule/SharedModule imports it.
For you case, i see you are extending the directive with Component class which is not acceptable to a Attribute directive :--
You should keep the Attribute Directive separate from any Component. For Ex: