Angular 2指令未调用

时间:2019-04-19 09:07:34

标签: angular

我的任务是使div文本中的url-s可点击。我开始学习Angular2。我创建了一条指令,并尝试使用linkifyjs模块。

指令:

import { Directive, ElementRef } from '@angular/core';
import linkifyStr from 'linkifyjs/string';

@Directive({selector: '[linkify]'})
export class LinkifyDirective {

  constructor(private el?: ElementRef) {
        console.log('CHECKPOINT1'); //THIS IS NOT PRESENT IN CONSOLE
        this.el.nativeElement.textContent = 'asd'; //THE TEXT IS DIFFERENT ON THE PAGE AFTER RENDERING, so this constructor is not even invoked.. ?
        this.el.nativeElement.textContent = this.transform(this.el.nativeElement.textContent);
  }

  private transform(str: string): string {
      return str ? linkifyStr(str, {target: '_system'}) : str;
  }
}

app.module.ts

import { LinkifyDirective } from './directives/linkify.directive';

@NgModule({   declarations: [
    AppComponent, LinkifyDirective   ],   exports: [
    AppComponent, LinkifyDirective ],

现有组件:

@Component({
  selector: 'app-event',
  templateUrl: 'event.template.html',
  styleUrls: ['event.style.scss']
})

export class EventComponent implements OnInit {

这里没有链接行。

带有linkify指令的** event.template.html

 <div class="text-wrap text-area-description" linkify name="description">
                                      {{event.description }}</div>

package.json:

"dependencies": {
...
"linkifyjs": "^2.1.5",
....

渲染的内容:

<div _ngcontent-c1="" class="text-wrap text-area-description" linkify="" name="description">
              Some sample text with address https://myip.com</div>

这里的问题是未调用linkify指令或类似的东西。没有CHECKPOINT1日志,尽管其中包含url,但该文本不会转换为可单击的文本。

  

一些地址为https://myip.com的示例文本

1 个答案:

答案 0 :(得分:1)

我注意到您的EventComponent没有在您的AppModule中声明。如果在单独的模块中声明了该参数,则需要在THAT模块中或在导入的模块中声明linkifyDirective。

相关问题