2016-10-11 2 views
0

В старой версии угловому 2 я мог бы импортировать директивы как import {CounterDirective} from './counter.directive';Угловые 2 директивы и модули

и использовать его.

С момента создания нового модуля приложения я не смог найти документацию о том, как создать собственный модуль и импортировать его в свое приложение. Например, я создал директиву, используя Angular-CLI: ng g directive counter, чтобы создать счетчик для заданного числа. Это мой директивный код:

import { Directive,Output,Input,EventEmitter } from '@angular/core'; 

@Directive({ 
    selector: '[counter]' 
}) 
export class CounterDirective { 

    constructor() { } 

    @Output() countoChange = new EventEmitter(); 
    private _timer; 
    private _duration: number; 
    private _countTo: number; 
    private _countFrom: number; 
    private _step: number; 

    @Input() 
    set duration(duration) { 
     this._duration = parseFloat(duration); 
     this.run(); 
    } 

    @Input() 
    set countTo(countTo) { 
     this._countTo = parseFloat(countTo); 
     this.run(); 
    } 

    @Input() 
    set countFrom(countFrom) { 
     this._countFrom = parseFloat(countFrom); 
     this.run(); 
    } 

    @Input() 
    set step(step) { 
     this._step = parseFloat(step); 
     this.run(); 
    } 

    run() { 
     var _this = this; 
     clearInterval(_this._timer); 

     if (isNaN(_this._duration)) { 
      return false; 
     } 

     if (isNaN(_this._step)) { 
      return false; 
     } 

     if (isNaN(_this._countFrom)) { 
      return false; 
     } 

     if (isNaN(_this._countTo)) { 
      return false; 
     } 

     if (_this._step <= 0) { 
      console.info('Step must be greater than 0.'); 
      return false; 
     } 

     if (_this._duration <= 0) { 
      console.info('Duration must be greater than 0.'); 
      return false; 
     } 

     if (_this._step > _this._duration*1000) { 
      console.info('Step must be equal or smaller than duration.'); 
      return false; 
     } 

     var intermediate = _this._countFrom; 
     var increment  = Math.abs(_this._countTo - _this._countFrom)/((_this._duration * 1000)/_this._step); 

     _this.countoChange.emit(intermediate); 

     _this._timer = setInterval(function() { 
      if (_this._countTo < _this._countFrom) { 
       if (intermediate <= _this._countTo) { 
        clearInterval(_this._timer); 
        _this.countoChange.emit(_this._countTo); 
       } else { 
        _this.countoChange.emit(intermediate); 
        intermediate -= increment; 
       } 
      } else { 
       if (intermediate >= _this._countTo) { 
        clearInterval(_this._timer); 
        _this.countoChange.emit(_this._countTo); 
       } else { 
        _this.countoChange.emit(intermediate); 
        intermediate += increment; 
       } 
      } 
     }, _this._step); 
    } 

} 

Как я могу импортировать его с помощью своего AppModule и использовать его?

+0

намек: у вас есть опечатка в названии вопроса –

ответ

0

Если вы хотите создать свой собственный модуль для директивы, вам нужно как объявить его в declarations и экспортировать его в exports

@NgModule({ 
    declarations: [ CounterDirective ], 
    exports: [ CounterDirective ] 
}) 
class CounterModule {} 

И тот, кто хочет использовать его, необходимо импортировать CounterModule

@NgModule({ 
    imports: [ CounterModule ] 
}) 
class SomeModule {} 

Помните, что все, в declarations (компонентов, директивы и трубы) никоим образом не унаследовали. Это означает, что только импорт CounterModule в AppModuleне будет предоставить доступ к нему во всех других модулях. Независимо от того, какой модуль вам нужен, используйте CounterDirective, вам необходимо импортировать CounterModule.

Если директива используется только жгутов в AppModule, то все, что вам нужно будет сделать, это добавить директиву AppModuledeclarations

Смежные вопросы