簡體   English   中英

指令中的Angular(2&4)訪問模板變量參考

[英]Angular (2 & 4) Access template variable reference from Directive

我有一個指令,目標是在前綴字段文本組件下添加建議列表。 該組件基本上是一個搜索欄。

我的指令當前如下所示(在我所有的代碼段中,我刪除了導入以增加可讀性):

@Directive({
    selector: '[prefixSuggest]',
    exportAs: 'prefixSuggest',
    host: {
      'class': 'prefix-field-suggest__container'
    }
  })
  export class PrefixFieldSuggestDirective implements AfterViewInit {

    private componentReference: ComponentRef<PrefixFieldSuggestComponent>;

    @Input() fieldTextRef: ElementRef;
    @Input() list: Array<PrefixSuggestLineInterface>;
    @ViewChild('fieldTextRef', {read: ViewContainerRef}) fieldTextContainer;

    constructor(private _injector: Injector, private resolver: ComponentFactoryResolver) {
        this.resolver.resolveComponentFactory(PrefixFieldSuggestComponent);
    }

    ngAfterViewInit(): void {
        const prefixFieldSuggestFactory = this.resolver.resolveComponentFactory(PrefixFieldSuggestComponent);
        this.componentReference = prefixFieldSuggestFactory.create(this._injector);
        this.componentReference.instance.list = this.list;
        this.fieldTextContainer.insert(this.componentReference.hostView);
    }
  }

我的組件看起來像這樣:

@Component({
  selector: 'prefix-field-suggest',
  templateUrl: './prefix-field-suggest.component.html',
  styleUrls: ['./prefix-field-suggest.component.scss']
})
export class PrefixFieldSuggestComponent {

    /** Item list to display */
    @Input() list: Array<PrefixSuggestLineInterface>;

    /** Search string typed in search input */
    @Input() searchTerm: string;

    /** Input ID to align itself beneath */
    @Input() inputId: string;

    /** Offset between the suggest and the input; default 0 */
    @Input() offset: number = 0;

    /** Event when an item is selected */
    @Output() itemSelected: EventEmitter<any>;
}

PrefixFieldSuggestComponent的模板文件:

<div class="prefix-field-suggest" 
    [ngStyle]="{ 'top': offset + 'px'}">
    <span *ngFor="let item of list">
        {{item.title | prefixBoldifyTerm:searchTerm}} {{item.metaData}}
    </span>
</div>

PrefixSuggestLineInterface只是一個契約接口,因此我們團隊中的不同人員可以根據他們想要在其中顯示的信息來實施自己的建議行。 ATM基本上是2個字符串字段。

問題:我想從我的指令中訪問prefix-field-ext(搜索欄)組件的ViewContainerRef。 我嘗試了很多事情,例如#[fieldTextRef],#[fieldTextRef] =“ mysearchbar”,fieldTextRef等...。

我在這個簡單的頁面上嘗試了這些可能性:

 <div class="prefix-search-group">
          <prefix-field-text prefixSuggest #fieldTextRef="prefixSuggest" list="list" [identifier]="search"></prefix-field-text>
 </div>

但是在每種情況下,我的fieldTextRef輸入始終為null。 (因為它不是子元素)。 甚至有可能做我想做的事情?

非常感謝您的啟發。

如果要獲取<prefix-field-text prefixSuggest ViewContainerRef ,只需將其注入構造函數prefixSuggest指令中,因為它應用於相同的元素:

export class PrefixFieldSuggestDirective implements AfterViewInit {
  constructor(private fieldTextContainer: ViewContainerRef,...) {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM