在离子模式中使用自定义指令

时间:2020-02-06 09:16:57

标签: angular ionic-framework modal-dialog directive

我有这个 ion-textarea autosize指令

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

@Directive({
  selector: 'ion-textarea[autosize]'
})
export class AutoResizeTextareaDirective {
  readonly defaultHeight = 64;

  @HostListener('input', ['$event.target'])
  onInput(textArea: HTMLTextAreaElement) {
    this.adjust(textArea);
  }

  constructor(private element: ElementRef) {}

  ngAfterViewInit() {
    this.adjust();
  }

  adjust(textArea?: HTMLTextAreaElement) {
    textArea = textArea || this.element.nativeElement.querySelector('textarea');

    if (!textArea) {
      return;
    }

    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height =
      (textArea.value ? textArea.scrollHeight : this.defaultHeight) + 'px';
  }
}

在我的 modal.component.html 中:

<ion-textarea autosize [(ngModel)]="message.msg_text"></ion-textarea>

该指令也已添加到我的app.module.ts中。这似乎不起作用,因为我怀疑这是该字段处于模态的事实。由于模态不包含.module.ts文件,我将如何在模态上使用它

2 个答案:

答案 0 :(得分:0)

似乎您的问题是命名的方式,请参见以下示例:

import { Directive } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor() { }
}

---
<p appHighlight>Highlight me!</p>

我认为您的选择器必须是:[autosize]而不是'ion-textarea[autosize]'

看看:Angular Attribute Directives Guide

答案 1 :(得分:0)

我设法找到了解决方案。无需将指令添加到app.module.ts的声明中,而是在页面的module.ts文件中声明它,您可以从以下位置打开模式