【问题标题】:How can i access to property of some directive from another directive我如何从另一个指令访问某些指令的属性
【发布时间】:2021-09-30 13:51:09
【问题描述】:

我有一个指令

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

@Directive({
  selector: '[appDirOne]',
  exportAs: 'appDirOne'
})
export class DirOneDirective {
  status: boolean = false;
  constructor() { }
}

在我的另一个指令中 - 当我点击我的情况下的托管元素时,我想要访问第一个指令的属性值的按钮。

  <button appDirTwo>Btn</button>

第二个指令

import { DirOneDirective } from './dir-one.directive';

@Directive({
  selector: '[appDirTwo]',
  exportAs: 'appDirTwo'
})
export class DirTwoDirective {
  @HostListener('click') onClick() {
    // access to the status property value of the directiveOne
  }

}

我尝试了什么

我尝试在构造函数中添加它

import { DirOneDirective } from './dir-one.directive';

@Directive({
  selector: '[appDirTwo]',
  exportAs: 'appDirTwo'
})
export class DirTwoDirective {
  constructor(private directiveOne: DirOneDirective) { }
  @HostListener('click') onClick() {
  }

}

但我明白了

core.js:4197 ERROR NullInjectorError: R3InjectorError(AppModule)[DirOneDirective -&gt; DirOneDirective -&gt; DirOneDirective]: NullInjectorError: No provider for DirOneDirective!

错误。

我想提一下,这两个指令都在我的 app.module.ts 文件中。

例如,如果我尝试在 HTML 中使用我的directiveOne

  <button appDirOne>Btn</button>

然后我没有此提供程序错误消息。 仅当我尝试在其他指令中作为服务注入时才会发生这种情况。

【问题讨论】:

  • 基本上,如果你想在指令之间共享数据,你需要一个服务。

标签: angular angular-directive


【解决方案1】:

首先,您需要为此考虑另一种方法。例如,请阅读有关passing inputs to an attribute directives 的官方文档或利用服务方法。

回到我们的问题。这确实是不好的建议,但您可以将您的DirOneDirective 导入DirTwoDirective 并创建DirOneDirective 的实例,例如在DirTwoDirectiveconstructor 中。比如:

第一条指令:

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  status: boolean = false;
  constructor(private el: ElementRef) {}
}

第二条指令:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

@Directive({
  selector: '[appHighweight]'
})
export class HighweightDirective {
  constructor(private el: ElementRef) {
    const highLDir = new HighlightDirective(this.el);
    console.log(highLDir.status); // false
  }
}

Stackblitz example

【讨论】:

  • 永远不要使用new创建指令或组件,绝对不是解决op的问题。
  • 我已经写过,因此这是一个糟糕的建议,并且操作需要另一种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 2016-06-17
  • 1970-01-01
  • 2012-08-08
  • 2021-09-29
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多