【问题标题】:Ionic 3 Directive Not Working离子 3 指令不起作用
【发布时间】:2017-09-07 13:32:21
【问题描述】:

我一直在尝试在 ionic 中创建一个指令,但它只是不起作用,我似乎不知道为什么。 我希望该指令能够自动调整自身大小。因此,当它有更多文本时,它只会不断调整大小。

这是我的代码: 我的项目是一个ionic 3项目,它使用了新版本的angular 4。

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[auto-resize-text-input]' // Attribute selector
})
export class AutoResizeTextInput {
  constructor(public elem: ElementRef) {
    console.log('Hello AutoResizeTextInput Directive');
  }

  @HostListener('input', ['$event.target']) onInput() {
    this.resizeTextOnInput();
  }

  private resizeTextOnInput() {
    this.elem.nativeElement.style.overflow = 'hidden';
    this.elem.nativeElement.style.height = 'auto';
    this.elem.nativeElement.style.height = this.elem.nativeElement.scrollHeight + "px";
  }
}

请帮忙????

【问题讨论】:

标签: angular typescript ionic2


【解决方案1】:

如果您将指令文件放在 components 文件夹中。这是答案:

将您的文件从 components/your-directive directives/your-directive 然后重建它。祝你好运!

【讨论】:

  • 实际在directives文件夹中,不知道怎么回事,代码看起来还不错
  • 正如您在 ionic 3 中所知道的,任何页面都有一个文件 page.module.ts 。当你想使用任何组件时,指令..你必须在这里导入你的指令
  • @BitaHo 答案应该可以。我从 app.module.ts 中删除了导入并将其添加到 page.module.ts 文件中,指令开始工作。
  • @BitaHo 你是否也将它添加到了directive.module.ts 中?
【解决方案2】:

我遇到了同样的问题。应用程序无法识别该指令,但它没有给出任何错误。所以我把它从主模块的decalarations中删除,并添加到使用指令的页面模块decalarations中,问题就消失了。

【讨论】:

  • 对我有用 - 将指令声明移动到组件的 module.ts 也对我有用。
  • 如果指令再次添加到另一个模块它不起作用。它给出了一个错误,说明该指令是 2 个模块声明的一部分。
【解决方案3】:

也许这会对你有所帮助:

如果您在组件中使用指令,请将directives.module.ts 导入app.module.tscomponents.module.ts 或直接将其导入app.module.ts 以在页面中使用您的指令。

【讨论】:

    【解决方案4】:

    如果您像我一样需要跨多个组件的此指令,这就是我的解决方法。

    在与您的app.module.ts 文件相同的文件夹中创建一个名为directives.module.ts 的共享DirectiveModule,并在declarations:[]exports:[] 下添加您尝试使用的指令:

    import { NgModule } from '@angular/core';
    import { SomeDirective } from './some.directive';
    
    @NgModule({
      declarations: [SomeDirective],
      exports: [SomeDirective]
    })
    export class DirectivesModule {}
    

    现在在你需要的模块中导入共享指令模块:

    import { NgModule } from '@angular/core';
    import { IonicPageModule } from 'ionic-angular';
    import { SomePage } from './some';
    import { DirectivesModule } from '../../app/directives.module';
    
    @NgModule({
      declarations: [
        DashboardPage
      ],
      imports: [
        IonicPageModule.forChild(SomePage),
        DirectivesModule
      ]
    })
    export class SomePageModule {}
    

    我在其他任何地方都找不到我正在寻找的答案,希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-20
      • 2018-03-11
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多