我有两天角度2的问题,我来找你们的帮助。
问题是当我尝试从父组件访问在ContentChild或ContentChildren中声明的指令子元素时,Angular找不到任何子元素。如果我不使用模板标签,我的父组件会找到没有问题的孩子。
父ngAfterContentInit和ngAfterViewInit显示子QueryBox没有结果
我的代码是:
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.');
}
}
嗯,那就是它,我等待一些帮助,因为我不知道如何解决这个问题。
由于