我有一个组件,它的模板如下所示:
<div [my-custom-directive]>Some content here</div>
我需要访问这里使用的MyCustomDirective
类实例。当我想访问子组件时,我使用ViewChild
查询。
有没有一个等效的特性来访问一个子指令?
发布于 2016-04-01 00:13:00
您可以使用@Directive
注释的exportAs
属性。它导出要在父视图中使用的指令。在父视图中,您可以将其绑定到视图变量,并使用@ViewChild()
从父类访问它。
使用plunker的示例
@Directive({
selector:'[my-custom-directive]',
exportAs:'customdirective' //the name of the variable to access the directive
})
class MyCustomDirective{
logSomething(text){
console.log('from custom directive:', text);
}
}
@Component({
selector: 'my-app',
directives:[MyCustomDirective],
template: `
<h1>My First Angular 2 App</h1>
<div #cdire=customdirective my-custom-directive>Some content here</div>
`
})
export class AppComponent{
@ViewChild('cdire') element;
ngAfterViewInit(){
this.element.logSomething('text from AppComponent');
}
}
更新
正如评论中提到的,除了上述方法之外,还有另一种选择。
可以直接使用@ViewChild(MyCustomDirective)
或@ViewChildren(MyCustomDirective)
,而不使用exportAs
以下是演示这三种方法之间的区别的一些代码:
@Component({
selector: 'my-app',
directives:[MyCustomDirective],
template: `
<h1>My First Angular 2 App</h1>
<div my-custom-directive>First</div>
<div #cdire=customdirective my-custom-directive>Second</div>
<div my-custom-directive>Third</div>
`
})
export class AppComponent{
@ViewChild('cdire') secondMyCustomDirective; // Second
@ViewChildren(MyCustomDirective) allMyCustomDirectives; //['First','Second','Third']
@ViewChild(MyCustomDirective) firstMyCustomDirective; // First
}
更新
发布于 2017-04-07 17:43:58
看起来自从@Abdulrahman的回答之后,就不能再从@ViewChild
或@ViewChildren
访问指令了,因为这些指令只传递DOM元素本身上的项。
相反,您必须使用@ContentChild
/@ContentChildren
访问指令。
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 App</h1>
<div my-custom-directive>First</div>
<div #cdire=customdirective my-custom-directive>Second</div>
<div my-custom-directive>Third</div>
`
})
export class AppComponent{
@ContentChild('cdire') secondMyCustomDirective; // Second
@ContentChildren(MyCustomDirective) allMyCustomDirectives; //['First','Second','Third']
@ContentChild(MyCustomDirective) firstMyCustomDirective; // First
}
@Component
属性上也不再有directives
属性。
发布于 2019-10-24 20:38:30
自2019年以来唯一剩下的解决方案
正如在其他答案的注释中所提到的,这些其他(以前有效的)方法不能与更新版本的Angular一起使用。
然而,值得庆幸的是,还有一种更简单的方法来注入它:直接从构造函数!
@Component({
// ...
})
export class MyComponent implements OnInit {
// Would be *undefined*
// @ContentChild(MyDirective, { static: true })
// private directive: MyDirective;
constructor(private directive: MyDirective) { }
ngOnInit(): void {
assert.notEqual(this.directive, null); // it passes!
}
}
https://stackoverflow.com/questions/36345618
复制相似问题