如何在角度2中调用特定的同级方法

时间:2018-08-29 09:18:59

标签: angular

from first component i want to call second component methode. 

export class FirstComponent {
            constructor(private _service: CommonService) {}
            }

这是第二个组件...将使用onngInit方法的构造函数。

 export class SecondComponent {
          constructor(private _service: CommonService) { }

          callMyMethod(){

          }
        }

1 个答案:

答案 0 :(得分:0)

您可以导入第二个组件,使用该组件的实例可以访问方法

这是例子

first.component.ts

import { Component, OnInit } from '@angular/core';
import { SecondComponent } from '../second/second.component';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css'],
  providers: [SecondComponent]

})
export class FirstComponent implements OnInit {

  constructor(public second: SecondComponent) { }

  ngOnInit() {
    console.log(this.second.getMessage());
  }

}

first.component.html

<p>
    welcome <b>{{second.getMessage()}}</b>
</p>

second.component.ts

import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {

  constructor() { }

  ngOnInit() {

  }

  getMessage(){
    return "This is second component";
  }

}

这是Stackblitz演示。