angular中父子组件传值(一)

 子组件使用父组件的方法变量

  1. 使用ng g component 组件名称下载两个组件
    ng g component components/father
    
    ng g component components/son
    
    
  2. 在根组件app.module.ts中引入父子组件并声明

    import { FatherComponent } from './components/father/father.component';
    import { SonComponent } from './components/son/son.component';
    
    
      declarations: [
        AppComponent,
        NewsComponent,
        FatherComponent,
        SonComponent
      ]
  3. 在根组件中使用父组件

    <app-father></app-father>

      

  4. 父组件中使用子组件并把方法和变量传给子组件

    <app-son [msg]="msg" [run]="run" [getDataFromChild]="getDataFromChild"> <!--把父组件中的meg信息流向子组件 []中的为方法名或值 可以自定义 ""号中的为 -->
    
    </app-son>

     父组件中声明方法和变量

      public msg = "我是父组件的信息";
    
      run(){
        alert("这是父组件的方法!!!")
      }
    
      getDataFromChild(childData){
        alert(childData);
      }
  5. 子组件中引入Input

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

    子组件获取父组件的方法和变量

      @Input()  msg:String;
      @Input()  run:any;
      @Input() getDataFromChild;

    子组件中使用父组件的方法和变量

    <h2> {{msg}}</h2>
    <button (click)="run()">方法</button>

    父组件获取子组件的变量

1.子组件声明自己的变量方法

通过调用自己的方法使用父组件传过来的方法传递自己的信息


  public sonMsg = "子组件的信息传递!!!!"

 doPost(){
       this.getDataFromChild(this.sonMsg);
  }

猜你喜欢

转载自blog.csdn.net/qq_42221135/article/details/83892913