1. 程式人生 > >angular4中父元件如何呼叫子元件的方法

angular4中父元件如何呼叫子元件的方法

一、新建一個子元件

ng g component child

二、子元件中新增要被呼叫的方法

child.component.ts

export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  greeting(name:string){
    console.log('hello'+name);
  }
}

三、主元件新增html程式碼

此處用2種方法呈現效果:

app.component.html

<!--1.在控制器裡用typescript程式碼實現-->
<app-child #child1></app-child> <!--2.在模板上用模板變數實現--> <app-child #child2></app-child> <button (click)="child2.greeting('Jerry')">按鈕呼叫child2的greeting方法</button>

四、主元件控制器加相關呼叫

app.component.ts

export class AppComponent implements OnInit{

  @ViewChild('child1'
) child1:ChildComponent; ngOnInit(): void { this.child1.greeting('tom'); } }

五、執行效果

這裡寫圖片描述