2017-08-30 20 views
5

tôi đã có thể nâng cấp một chỉ thị yếu tố angularjs được sử dụng trong góc 4. Dưới đây là một số mẫu mã:Có thể nâng cấp angularjs chỉ thị để sử dụng trong góc 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); 
    } 
} 

Lưu ý Tôi đang sử dụng UpgradeComponent để nâng cấp chỉ thị phần tử myScores. Tôi đã thử cùng một chỉ thị thuộc tính nhưng đã gặp lỗi. Có cách nào để nâng cấp chỉ thị thuộc tính không?

Đây là nỗ lực của tôi về việc nâng cấp một chỉ thị thuộc tính:

[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); 
    } 
} 

tôi nhận được một thông báo lỗi khi tải một trang có nội dung như sau:

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

Tôi đã nhận lỗi này:

Error: Directive 'makeGreen' is not a component, it is missing template. 

Trả lời

0

Khác với góc < 2, trong 2+ góc, Directives thêm hành vi để một yếu tố DOM hiện tại hoặc một hiện instance của component. Tôi nghĩ rằng trường hợp sử dụng của bạn khớp với một thành phần thay vì chỉ thị. Một thành phần góc nên được cung cấp mẫu nội tuyến template hoặc theo đường dẫn đến html templateUrl. Mặc dù bạn đã chú thích số class MakeGreenDirective@Directive, nó được mở rộng từ Component. Bạn sẽ phải chú thích lớp học với @Component và cung cấp mẫu.

@Component({ 
    selector: '[makeGreen]', 
    templateUrl: './make-green.component.html', 
}) 

tham khảo this answer để biết thêm thông tin về sự khác biệt

Các vấn đề liên quan