我正在尝试将 AngularJS 指令转换为 Angular。使用ngUpgrade
.
我有 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>
组件.ts:
test() {
return 'something';
}