我正在尝试使用Material 2 sidenav计算如何在子组件模板点击事件#rightNav
中触发父组件模板中的本地引用,即(click)="rightNav.open()"
。我想我需要使用@ViewChild
注释,但不确定如何。
子组件模板(app-conditions-list):
<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition"
(click)="rightNav.open()"></div>
父组件模板(条件组件):
import { Component} from '@angular/core';
import { ConditionsListComponent } from './listComponent/conditions-list.component';
@Component({
moduleId: module.id,
selector: 'app-conditions',
template: `
<md-sidenav #rightNav align="end" mode="side">
"Condition details will open here on click event"
</md-sidenav>
<app-conditions-list></app-conditions-list>`,
styleUrls: ['./conditions.component.css'],
directives: [
ConditionsListComponent,
]
})
export class ConditionsComponent {
title = "Conditions Manager"
}
子组件嵌套在父组件模板中。 谢谢!
答案 0 :(得分:1)
您可以向子组件添加输出并从中侦听事件
export class ConditionsListComponent {
@Output() navOpen:EventEmitter = new EventEmitter();
}
您可以使用模板变量来引用兄弟元素,如:
<div #rightNav align="end" mode="side" (close)="close($event)"</div>
<app-conditions-list (navOpen)="rightNav.open()"></app-conditions-list>`,
并举办像
这样的活动<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition"
(click)="navOpen.next(null)"></div>
答案 1 :(得分:1)
您需要将您的活动从您的孩子冒充到您的父母:
The child :
export class ConditionsListComponent {
@Output('myEvent') myEvent = new EventEmitter();
private bubbleUp($event:Event){
myEvent.emit($event)
}
}
它的观点:
<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition"
(click)="bubbleUp($event)"></div>
父母:
import { Component} from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-conditions',
template: `
<div #rightNav align="end" mode="side" (close)="close($event)"</div>
<app-conditions-list (myEvent)='gotTheEvent($event)' ></app-conditions-list>`,
styleUrls: ['./conditions.component.css'],
providers: [],
directives: [
ConditionsListComponent,
]
})
export class ConditionsComponent {
title = "Conditions Manager";
gotTheEvent($event){
console.log('I got this event from my child',$event);
//you can do whatever you want :
rightNav.open()
}
}