【问题标题】:Can an angular2 directive access the template of a component it's applied to?angular2 指令可以访问它所应用的组件的模板吗?
【发布时间】:2017-02-04 05:38:49
【问题描述】:

感谢 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 的实例。

【问题讨论】:

    标签: angular typescript angular2-directives


    【解决方案1】:

    指令没有视图,因此@ViewChild() 不起作用。 @ContentChildren() 是支持的。

    【讨论】:

    • 谢谢!那么指令有没有办法获取在其应用的组件的模板中定义的内容?例如。如果我将指令应用于我的组件 - my-custom-dropdown - 我的指令是否可以访问在 my-custom-dropdown 的模板中定义的另一个组件?
    • 我已经更新了我的问题,因为我更好地理解了我真正要问的问题。
    猜你喜欢
    • 2016-12-26
    • 2017-07-31
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多