Issue angular directives with Typescript

Hi, I am trying to implement the following angular directive using Typescript classes,
angular.module('mota.main', []).directive('modalDialog', function() { return { restrict: 'E', scope: { show: '=' }, replace: true, // Replace with the template below transclude: true, // we want to insert custom content inside the directive link: function(scope, element, attrs) { scope.dialogStyle = {}; if (attrs.width) scope.dialogStyle.width = attrs.width; if (attrs.height) scope.dialogStyle.height = attrs.height; scope.hideModal = function() { scope.show = false; }; }, templateUrl = 'src/app/selection.ts' }; }); 

This is the template:

  <div class='ng-modal' ng-show='show'> <div class='ng-modal-overlay' ng-click='hideModal()'></div> <div class='ng-modal-dialog' ng-style='dialogStyle'> <div class='ng-modal-close' ng-click='hideModal()'>X</div> <div class='ng- modal-dialog-content' ng-transclude></div> </div> </div> 

This is my approach

 export class ModalDialogDirective implements ng.IDirective { public restrict = "E"; public scope = {show: '='}; public require = ['ngModel']; public transclude = true; public templateUrl = 'src/app/selection.ts'; public replace = true; public link(scope: ng.IScope, element: JQuery, attrs: ng.IAttributes) { scope.dialogStyle = {}; if (attrs.width){ scope.dialogStyle.width = attrs.width; } if (attrs.height){ scope.dialogStyle.height = attrs.height; } scope.hideModal = function() { scope.show = false; }; } } 

This is his way of calling in html:

 <modal-dialog show='modalShown' width='400px' height='60%'> <p>Modal Content Goes here<p> </modal-dialog> 

I get problems like: The 'dialogStyle' property does not exist on type '{show: string; } ".

The 'width' property does not exist in the 'IAttributes' type.

An argument of type 'typeof ModalDialogDirective' is not assigned to a parameter of type 'any []'.

+5
source share
1 answer

Your link function must take an extended type scope. Declare an interface that extends ng.IScope to provide your options, and then use that interface in your link function:

 interface ImyScope extends ng.IScope{ dialogStyle:any; hideModal:()=>void; show:boolean; } public link(scope: ImyScope, element: JQuery, attrs: ng.IAttributes) { scope.dialogStyle:any = {}; if (attrs.width){ scope.dialogStyle.width = attrs.width; } if (attrs.height){ scope.dialogStyle.height = attrs.height; } scope.hideModal = function() { scope.show = false; }; } 

If you want some templates to get you started with angular and typescript, I suggest you check out SideWaffle: http://sidewaffle.com/

+5
source

Source: https://habr.com/ru/post/1215943/


All Articles