角度-从属性指令内部的元素中获取文本

时间:2019-03-21 11:48:47

标签: angular

我创建了一个Angular Attribute Directive,可以将其添加到按钮或链接中并实现某种点击跟踪。请在此处查看简化示例:

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

@Directive({
  selector: '[appTrackClick]'
})
export class TrackClickDirective {
  @Input() trackType = 'ButtonClick';
  @Input() trackName: string;

  @HostListener('click') onClick() {
    this.trackClick()
  }

  constructor() { }

  trackClick() {
    if (!this.trackName) {
      return false;
    }
    // Do the tracking...
  }
}

我希望this.trackName的值是单击的按钮或链接的文本。如何从元素获取此信息?

如果可能,我只想在Typescript中执行此操作,而不必在模板中添加更多标记。

1 个答案:

答案 0 :(得分:3)

您只需在指令中插入<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jg</groupId> <artifactId>lib1</artifactId> <version>1.1</version> <packaging>jar</packaging> <name>lib1</name> <build> <extensions> <extension> <groupId>org.codedoers.maven</groupId> <artifactId>bitbucket-download-wagon</artifactId> <version>1.1.0</version> </extension> </extensions> </build> <profiles> <profile> <id>codedoers</id> <repositories> <repository> <id>bitbucket</id> <url>bitbucket://jgoday:mypassword@jgoday/artifacts</url> </repository> </repositories> </profile> </profiles> <distributionManagement> <repository> <id>bitbucket</id> <name>bitbucket</name> <url>bitbucket://jgoday:mypassword@jgoday/artifacts</url> </repository> </distributionManagement> </project> 即可访问主机DOM元素。

您可以了解有关指令和ElementRef here的更多信息:

  

您可以在指令的构造函数中使用ElementRef注入对宿主DOM元素的引用,宿主DOM元素是您将指令应用到的元素。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>jg</groupId>
  <artifactId>lib2</artifactId>
  <version>1.0</version>
  <packaging>jar</packaging>

  <name>lib2</name>
  <build>
    <extensions>
        <extension>
            <groupId>org.codedoers.maven</groupId>
            <artifactId>bitbucket-download-wagon</artifactId>
            <version>1.1.0</version>
        </extension>
    </extensions>
  </build>

  <dependencies>
    <dependency>
      <groupId>jg</groupId>
      <artifactId>lib1</artifactId>
      <version>1.1</version>
    </dependency>
  </dependencies>

  <profiles>
    <profile>
        <id>customrepos</id>
        <repositories>
            <repository>
                <id>bitbucket</id>
                <url>bitbucket://jgoday:mypassword@jgoday/artifacts</url>
            </repository>
        </repositories>
    </profile>
  </profiles>

  <distributionManagement>
    <repository>
        <id>bitbucket</id>
        <name>bitbucket</name>
        <url>bitbucket://jgoday:mypassword@jgoday/artifacts</url>
    </repository>
  </distributionManagement>
</project>