Подтвердить что ты не робот

Получить ссылку на директиву, используемую в компоненте

У меня есть компонент, чей шаблон выглядит примерно так:

<div [my-custom-directive]>Some content here</div>

Мне нужен доступ к MyCustomDirective класса MyCustomDirective используется здесь. Когда я хочу получить доступ к дочернему компоненту, я использую запрос ViewChild.

Есть ли эквивалентная функция для получения доступа к дочерней директиве?

4b9b3361

Ответ 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

}

Обновить

Еще один плункер с большим пояснением

Ответ 2

Похоже, что, поскольку @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.