我正在尝试将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';
}