簡體   English   中英

angular2指令可以訪問要應用到的組件的模板嗎?

[英]Can an angular2 directive access the template of a component it's applied to?

感謝Gunter的回答進行了更新,現在我更好地了解了我的要求:

如果我正在編寫自定義指令,並且計划將其應用於組件,那么讓我的指令查詢該組件模板的最佳方法是什么?

我正在寫一個屬性指令,其目的僅僅是改變它在其主機中找到的第一個自定義按鈕組件的樣式。 如果主機本身是我的自定義按鈕組件,則出於某種原因,它會顯示在我的指令的ContentChildren查詢中。 而且,如果主機在其模板中包含我的自定義按鈕組件,則我的指令找不到它。

這是我的指令:

import { Directive, AfterViewInit, AfterContentInit, ContentChildren, QueryList, ViewChild, ElementRef } from '@angular/core';
import { MyCustomButtonComponent } from './my-custom-button.component';

@Directive({
    selector: '[specialButton]'
})
export class SpecialButtonDirective implements AfterViewInit, AfterContentInit {

    hostElement: ElementRef;
    @ViewChild(MyCustomButtonComponent) myCustomButtonViewChild;
    @ContentChildren(MyCustomButtonComponent, {descendants: true}) myCustomButtonQueryList: QueryList<MyCustomButtonComponent>;

    constructor(el: ElementRef) {
        this.hostElement = el;
    }

    ngOnInit() {
        //Should I query here? Via this.hostElement.nativeElement.querySelector(...) perhaps?
    }

    ngAfterContentInit(): void {
        console.log('Value of myCustomButtonQueryList.first [' + this.myCustomButtonQueryList.first + ']');
    }
    ngAfterViewInit(): void {
        console.log('Value of myCustomButtonViewChild [' + this.myCustomButtonViewChild + ']');
    }
}

然后在我的主要組件中,該組件的指令中包括MyCustomButtonComponent和SpecialButtonDirective:

<my-custom-button specialButton>Host is Button</my-custom-button>
<!-- Value of myCustomButtonQueryList.first [[object Object]] -->
<!-- Value of myCustomButtonViewChild [undefined] -->

<!--The dropdown toggle button is a my-custom-button in my-custom-dropdown's template -->
<my-custom-dropdown specialButton>
    <ul>
        <li><div>Item 1</div></li>
        <li><div>Item 2</div></li>
    </ul>
</my-custom-dropdown>
<!-- Value of myCustomButtonQueryList.first [undefined] -->
<!-- Value of myCustomButtonViewChild [undefined] -->

我不明白為什么第一個示例會找到我的自定義按鈕組件,因為我認為ContentChildren僅在ng-content標簽內搜索,但是它正在拾取主機MyCustomButtonComponent。

而且我不明白為什么第二個示例不起作用,因為我認為ViewChild應該搜索my-custom-dropdown的模板? 但是,它沒有在其中找到MyCustomButtonComponent的實例。

指令沒有視圖,因此@ViewChild()將不起作用。 雖然支持@ContentChildren()

暫無
暫無

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

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