如果有多个子组件,如何从父对象访问子组件方法?

时间:2018-07-14 17:14:01

标签: angular5 parent-child viewchild

我正在从父视图中循环子组件。我想为每个子组件创建一个实例,并从父组件中调用每个子组件的实例方法。任何帮助将不胜感激!!!

父component.ts

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { CustomComponent } from './custom.component';

@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="let v of views">
       <customcomponent [name]="v" #cmp></customcomponent>
    </div>
    <hr/>
    <div>
      {{components?._results | json}}
    </div>
  `
})
export class AppComponent implements AfterViewInit {

  views = ['Sally','Manuel'];  
  @ViewChild('cmp') components:;

  ngAfterViewInit(){
    console.log( this.components.refreshMethod() );
  }

}

以下是子组件:

子component.ts

import { Component, OnInit, Input, OnChanges, Output, EventEmitter, AfterViewInit, } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { CustomerService } from '../../../services/customer-service/customer-service';

    @Component({
      selector: 'Customcomponent',
      templateUrl: "./CustomComponent.html",
      styleUrls: ['../widget.css'],
      // template:` haiiiii this is fromwidgets.`,
    })
    //  ----------------------inheritence binding concept--------------------------->start
    export class CustomComponent  implements OnInit, AfterViewInit {
      timerUnsubscribe: boolean;
      // ngAfterContentInit(): void {
      //   throw new Error("Method not implemented.");
      // }

      @Input() widget: any;


      @Output() event = new EventEmitter();

      public temp = [];
      needToRefresh: any;
      loader: boolean;

      constructor(public _custService: CustomerService) {
      }
      refreshMethod() {

      }

      ngOnDestroy() {
        console.log("Parent Destroy");
      }
    }

0 个答案:

没有答案