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("我是子组件的方法!!!")
       }

猜你喜欢

转载自blog.csdn.net/qq_42221135/article/details/83896486
今日推荐