[英]How to trigger local reference in parent component from child component event in Angular 2?
I am trying to work out how to trigger a local reference in a parent component template ie #rightNav
from a child component template click event (click)="rightNav.open()"
using Material 2 sidenav . 我正在尝试找出如何使用材料2 sidenav在子组件模板点击事件
(click)="rightNav.open()"
触发父组件模板(即#rightNav
的本地引用。 I think I need to use the @ViewChild
annotation, but not sure how. 我想我需要使用
@ViewChild
批注,但不确定如何使用。
Child component template (app-conditions-list): 子组件模板(app-conditions-list):
<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition"
(click)="rightNav.open()"></div>
Parent component template (condition component): 父组件模板(条件组件):
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"
}
The child component is nested in the parent component template. 子组件嵌套在父组件模板中。 Thanks!
谢谢!
You can add an output to the child component and listen to events from it 您可以将输出添加到子组件并从中监听事件
export class ConditionsListComponent {
@Output() navOpen:EventEmitter = new EventEmitter();
}
You can use a template variable to refer to sibling elements like: 您可以使用模板变量来引用同级元素,例如:
<div #rightNav align="end" mode="side" (close)="close($event)"</div>
<app-conditions-list (navOpen)="rightNav.open()"></app-conditions-list>`,
and event an event like 并发生类似的事件
<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition"
(click)="navOpen.next(null)"></div>
You'd need to bubble your event up from your child to your parent : 您需要将事件从孩子传给父母:
The child :
export class ConditionsListComponent {
@Output('myEvent') myEvent = new EventEmitter();
private bubbleUp($event:Event){
myEvent.emit($event)
}
}
It's view : 视图:
<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition"
(click)="bubbleUp($event)"></div>
And the parent : 和父母:
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.