【问题标题】:Triggering the other component function from my component using @viewChild使用 @viewChild 从我的组件触发其他组件功能
【发布时间】:2025-10-09 03:15:01
【问题描述】:

在我的应用程序中,我有多个组件,因为我必须从一个组件触发另一个组件功能。两个组件之间没有关系。在这种情况下尝试使用@viewChild。

调用函数时得到 TypeError: Cannot read property 'showHelp' of undefined error。

@viewChild 是否只用于父子组件交互,是否只能通过服务实现?

import { ChangeListComponent } from '../change-list/change-list.component';
    export class WeatherReportComponent {
        @ViewChild(ChangeListComponent) private changeListComponent:ChangeListComponent;
        showHelp(){
            this.changeListComponent.showHelp();
        }
    }

【问题讨论】:

    标签: angular


    【解决方案1】:

    下面是子组件,您可以在其中发送一些按钮点击值,下拉选择到父组件。单击按钮时,我们将从子组件触发childToParent 事件,其名称为值

    import { Component, Input, Output,EventEmitter } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      template: `
        <input type="textbox" [(ngModel)]='masterName'>
        <button (click)="sendToParent(masterName)" >sendToParent</button>
      `
    })
    export class AppChildComponent {
      //getting value from parent to child
      @Input('master') masterName: string;
    
      @Output() childToParent = new EventEmitter<String>();
    
      sendToParent(name){
        this.childToParent.emit(name);
      }
    }
    

    下面是主组件,其中childToParent方法是从具有发射值的子组件触发的。

    import { Component, Output,EventEmitter } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      //passing values from parent to child
      master = "child";
    
      //Getting value from child
      childToParent(name){
        this.master=name;
      }
    
    }
    

    You can refer this link for working version

    【讨论】:

    • 在我的应用中,两个组件之间没有链接。
    • 组件之间喜欢共享什么?如果您想在组件之间共享一些数据,请使用服务。
    最近更新 更多