我需要从Angular 2中的其他组件中获取公共方法

I need get public method from other component in Angular 2

本文关键字:获取 组件 方法 其他 Angular      更新时间:2023-09-26

我需要从app.component调用headerExpand属性,但当我尝试这样做时,请在控制台中显示:

metadata_resolver.js:559未捕获错误:无效的"Page1"提供程序-只允许提供程序和类型的实例,得到:[?)

page1.ts

<pre>
import { Component } from '@angular/core';
import { MyApp } from '../../app/app.component';
@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html',
})
export class Page1 {
  constructor(public miApp: MyApp) {
    console.log(miApp.headerExpand);
  }
</pre>

app.component.ts

<pre>
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  rootPage: any = Page1;
  public headerExpand: boolean;
  public pages: Array<{title: string, component: any}>;
  constructor(public platform: Platform) {
    this.initializeApp();
    this.headerExpand = true;

  }
  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
    });
  }
  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  expandHeader(){
    this.headerExpand = false;
  }
}

不能将父组件注入到子组件中。例如,你应该在这个场景中使用Output()。请看这里:

https://angular.io/docs/ts/latest/cookbook/component-communication.html