我已经能够升级angularjs元素指令以在角度4中使用。 这是一个示例代码:
[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);
}
}
注意我正在使用UpgradeComponent来升级myScores元素指令。 我在属性指令上尝试过相同但是出错了。有没有办法升级属性指令?
这是我尝试升级属性指令:
[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);
}
}
加载具有以下内容的页面时出错:
<div makeGreen>Text should be green</div>
我收到了这个错误:
Error: Directive 'makeGreen' is not a component, it is missing template.
答案 0 :(得分:1)
一个Attribute指令可以完全具有Input属性,可以从使用它的标记中将其传递给它:例如:
<p highlightThis [highlightColor]="'orange'" [count]="5">Highlighted in orange</p>
还要确保您的appModule / SharedModule导入了它。
所以我看到的问题是您定义结构的方式 指示。结构指令没有任何模板结构 附加到它。它适用于任何使用过的html标签。
对于您而言,我看到您正在使用Component class 扩展指令,而 Attribute指令则不可接受:-
MakeGreenDirective extends UpgradeComponent {
您应将属性指令与任何组件分开。例如:
import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from
'@angular/core';
@Directive({
selector: '[highlightThis]'
})
export class HighLightThisDirective {
@Input() count: number;
@Input() highlightColor: string;
@Output() clicked: EventEmitter<number>;
constructor(private elementRef: ElementRef, injector: Injector) { }
ngOnInit(): void {
this.decorateMyTag();
}
private decorateMyTag(): void {
console.log("highlightColor", this.highlightColor);
this.elementRef.nativeElement.style.backgroundColor = this.highlightColor;
}
}