Ответ 1
Вы можете использовать свойство exportAs
аннотации @Directive
. Он экспортирует директиву, которая будет использоваться в родительском представлении. Из родительского представления вы можете привязать его к переменной вида и получить доступ к ней из родительского класса с помощью @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');
}
}
Обновить
Как упоминалось в комментариях, существует еще одна альтернатива вышеуказанному подходу.
Вместо использования exportAs
можно напрямую использовать @ViewChild(MyCustomDirective)
или @ViewChildren(MyCustomDirective)
Вот какой код демонстрирует разницу между тремя подходами:
@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
}
Обновить