Templates 来自子模板元素的Angular 2 access指令
我对angular 2有两天的问题,我是来找你们帮忙的 问题是,当我尝试访问with ContentChild中声明的指令子级或父组件中的ContentChild时,Angular找不到任何子级。如果我不使用模板标记我的父组件,那么可以找到没有问题的子组件 父项ngAfterContentInit和ngAfterViewInit显示子项QueryList没有结果 我的代码是:Templates 来自子模板元素的Angular 2 access指令,templates,angular,parent-child,Templates,Angular,Parent Child,我对angular 2有两天的问题,我是来找你们帮忙的 问题是,当我尝试访问with ContentChild中声明的指令子级或父组件中的ContentChild时,Angular找不到任何子级。如果我不使用模板标记我的父组件,那么可以找到没有问题的子组件 父项ngAfterContentInit和ngAfterViewInit显示子项QueryList没有结果 我的代码是: import { Component } from '@angular/core'; import {ParentCo
import { Component } from '@angular/core';
import {ParentComponent} from './components/parent.component';
import {ChildDirective} from './components/child.directive';
@Component({
selector: 'my-app',
template: `
<parent>
<template>
<button child>button 1 with child directive</button>
<button child>button 2 with child directive</button>
</template>
</parent>
`,
directives: [ParentComponent, ChildDirective]
})
export class AppComponent { }
好了,就这样,我在等待帮助,因为我不知道该怎么解决这个问题
谢谢
import {Component, ContentChild, ContentChildren, QueryList,
TemplateRef, AfterContentInit, AfterViewInit} from '@angular/core';
import {ChildDirective} from './child.directive';
@Component({
selector: 'parent',
template: `
Parent Template
<br/>
<br/>
<template [ngTemplateOutlet]="template"></template>
`
})
export class ParentComponent implements AfterContentInit, AfterViewInit{
@ContentChild(TemplateRef)
template:TemplateRef;
@ContentChildren(ChildDirective)
children:QueryList<ChildDirective>;
ngAfterContentInit(){
console.log(this.children);
}
ngAfterViewInit(){
console.log(this.children);
}
}
import {Directive, OnInit, HostListener, EventEmitter, Output} from '@angular/core';
@Directive({
selector: '[child]',
})
export class ChildDirective implements OnInit{
ngOnInit(){
console.log('child started');
}
@Output()
onClick:EventEmitter = new EventEmitter;
@HostListener('click')
onMouseEnter() {
console.log('clicked');
this.onClick.emit('the child has been clicked.');
}
}