4

I am trying to convert AngularJS directives to Angular. Running AngularJS and Angular together using ngUpgrade.

I have AngularJS directive as below:

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

converted to 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 is not being called when clicked on the

Downgrade the above migrated directive to AngularJS so it can be used in AngularJS template

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

AngularJS template:

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

component.ts:

test() {
    return 'something';
}
Dot Net Dev
  • 574
  • 8
  • 20
  • 5
    You could add a wrapper component and downgrade that component afterwards. Take a look at this discussion: https://github.com/angular/angular/issues/16695 – Koen Meijer Feb 03 '19 at 19:55

0 Answers0