1. 程式人生 > >angular父子元件傳值(二)

angular父子元件傳值(二)

父類元件應用子類元件的方法和變數

  1. 根元件中引入父子元件
    import { Son2Component } from './components/son2/son2.component';
    import { Father2Component } from './components/father2/father2.component';
    declarations: [
        AppComponent,
        NewsComponent,
        Son2Component,
        Father2Component
      ],

    在根元件中使用父元件

    <app-father2></app-father2>

     

  2. 父元件引入ViewChild (重要)

    import { Component, OnInit,ViewChild } from '@angular/core';
    /** son2為呼叫子元件時取得別名 定義為子元件*/
     @ViewChild("son2") son2;
    
    /** 父類的方法*/
       getMessage(){
         alert(this.son2.name);
       }
       getWay(){
         this.son2.way();
       }

    父元件引入子元件 並給子元件取別名 與上面的son2對應好

    <!--呼叫子元件時給子元件取別名 -->
    <app-son2 #son2></app-son2>
    

    獲取子元件的方法的變數

    {{son2.name}}
    <button (click)="getMessage()">獲取子元件的變數</button>
    <button (click)="getWay()">獲取子元件的方法</button>

     

  3. 子元件的變數和方法

     
      public name = "我是子元件的變數資訊!!!!"   
      way(){
          alert("我是子元件的方法!!!")
       }