降级Angular指令并在AngularJS模板中使用

时间:2019-01-16 19:47:10

标签: angularjs angular ng-upgrade

我正在尝试将AngularJS指令转换为Angular。使用ngUpgrade一起运行AngularJS和Angular。

我有如下AngularJS指令:

angular.directive('countClicks', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            scope.clickCount = 0;
            elem.on('click', function() {
                // Code
            });
        }
    };
});

已转换为Angular

@Directive({
    selector: '[count-click]'
})

export class CountClickDirective implements AfterViewInit {
    constructor(public elem: ElementRef) { }
    clickCount = 0;

    ngAfterViewInit() {
        this.elem.nativeElement.querySelector('count-click', addEventListener('click', function() { 
            console.log('test directive'); 
        }));
    }
}
点击

时未调用

ngAfterViewInit

将上面迁移的指令降级到AngularJS,以便可以在AngularJS模板中使用

.directive('countClick', <any>downgradeComponent({
    component: CountClickDirective,
}))

AngularJS模板:

<span countClick ng-click="test()"></span>

component.ts:

test() {
    return 'something';
}

0 个答案:

没有答案