是否有可能升级angularjs atttribute指令以在角度4中使用?

前端之家收集整理的这篇文章主要介绍了是否有可能升级angularjs atttribute指令以在角度4中使用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经能够升级 angularjs元素指令以在角度4中使用.
这是一个示例代码

[myscores.js]

angular.module('app.components.directives.myscores',[])
.directive('myscores',function() {
  return {
    scope: {
      score: '=',},template: '<div>&gt;&gt;&gt; Your score is {{score}} &lt;&lt;&lt;',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,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',injector);
  }
}

加载具有以下内容页面时出错:

<div makeGreen>Text should be green</div>

我收到了这个错误

Error: Directive 'makeGreen' is not a component,it is missing template.
Attribute指令可以完全具有Input属性,该属性可以从使用它的标记传递给它:例如:
<p highlightThis [highlightColor]="'orange'" [count]="5">Highlighted in orange</p>

还要确保你的appModule / SharedModule导入它.

So the problem i see is with the way you are defining your structural
directive. A structural directive doesn’t have any template structure
attached to it. It applies to any html tag where it’s used.

对于你的情况,我看到你正在使用Component类扩展指令,这是Attribute指令不能接受的: –

MakeGreenDirective extends UpgradeComponent {

您应该将Attribute Directive与任何Component分开.对于Ex:

import { Directive,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;
  }
}
原文链接:/angularjs/141747.html

猜你在找的Angularjs相关文章