【问题标题】:How to trigger local reference in parent component from child component event in Angular 2?如何从Angular 2中的子组件事件触发父组件中的本地引用?
【发布时间】:2016-11-27 19:31:45
【问题描述】:

我正在尝试使用Material 2 sidenav 从子组件模板单击事件(click)="rightNav.open()" 中触发父组件模板中的本地引用,即#rightNav。我想我需要使用@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"
}

子组件嵌套在父组件模板中。 谢谢!

【问题讨论】:

  • 对我来说,我不清楚 &lt;md-list-item&gt;&lt;md-sidenav&gt; 是如何相关的。 “父组件”是什么意思?
  • 感谢@GünterZöchbauer。我清理了代码以删除不相关的代码。父组件是#rightNav 引用所在的位置。
  • 请添加更多代码。对我来说,仍然完全不清楚您要完成什么。
  • condition-list 组件的选择器是什么?

标签: angular typescript components angular-material2


【解决方案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>

【讨论】:

    【解决方案2】:

    您需要将您的活动从您的孩子传递给您的父母:

    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()
      }
    }
    

    【讨论】: