【问题标题】:How can I access to my content projected directive?如何访问我的内容投影指令?
【发布时间】:2021-07-26 21:41:17
【问题描述】:

我有一个form-field 组件。在里面我正在投影内容 - 输入 html 元素。在那个元素上,我附加了名为 autoCompletition 的指令。

 <app-form-field>
     <input [id]="autoCompleteSearchInput" [formControl]='search' type="text" autoComplete="off"
        class='input-underline search-bar idented-text' placeholder="Enter" autoCompletion 
        #custom="autoCompletion"/>
 </<app-form-field>
<form>
    <p>form-field works!</p>
    <ng-content></ng-content>
</form>

我需要访问托管在输入上的指令。所以如果我给它起名字: #custom="autoCompletition 我可以像这样访问我的组件:

 @ContentChild('custom')
  directive?: ElementRef;

 ngAfterContentInit() {
  console.log('this.directive);
}

这种方法的问题是指令是硬编码的——所以它被称为custom。我需要一种使其可自定义的方法 - 所以它应该适用于任何名称。

如果我将父组件称为#someOtherName="autoCompletition",我需要从app-form-field 自动访问该指令的引用。

我该怎么做?

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以通过类名而不是给定名来访问它

      // assuming a directive like so
      @Directive({...})
      class AutoCompleteDirective {...}
     
      // in the component
      @ContentChild(AutoCompleteDirective)
      directive!: AutoCompleteDirective;
    

    【讨论】:

    • @codebrach 但我如何才能听到指令中的变化?
    • 如果指令中的更改是指在指令的现有实例中,那么您可以调用指令中存在的方法。您可以获得指令的实际实例(更新代码)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2019-04-19
    • 2021-10-03
    相关资源
    最近更新 更多