子组件调用父组件

子组件调用父组件的内容(数据,函数),使用Input/output

方法一:(Input)

  1. 子组件ts中中引入Input   
    import { Input } from '@angular/core';
  2. 子组件ts中的   export class XXXXComponent implements OnInit{}中使用@input() 来接收
     @Input() dataInit:any;
  • 例子
    • 子组件中使用@input   
      @Input() phoneDisabled:any;
    • 把子组件引入父组件中   
      <app-phone  [phoneDisabled] =PhoneDisabled "></app-phone>
    • 父组件内进型声明  
      public phoneDisabled:boolean = false;
    • 在子组件的ts中定义一个函数
      <app-header [ChildMessage]="message"></app-header>
    • 子组件中进行调用  
       message(){
          console.log(this.ChildMessage);
        }
      即可

 方法二:(output)

  1.  在子组件的ts中添加output 和 EventEmitter注入  
      import { Component, OnInit ,Output,EventEmitter } from '@angular/core';
  2.  export class HeaderComponent implements OnInit{}中使用接收   
      @Output() public  outer = new EventEmitter<string>(); 仅仅改变的只是红色的部分,其他部分照写即可
  3.  在父组件的html中引入子组件  
      <app-header  (outer)="outMessage()"></app-header>
  4.  在父组件的ts中写一个函数  
      public outMessage(){
          alert("使用outPut来调用父级数据");
        };
  5.  在子组件的html中写一个方法        
      <button (click)="parents()">父组件调用子组件的数据</button>

   6 在子组件的ts中进行一次调用

     parents(){
         this.outer.emit();
      }
    即可

  注释:2中的outer【子组件ts中的声明 outer】必须和3中的(outer)【父组件中的】一致,
     3中的outMessage()【父组件html中的】必须和4中的函数名【子组件ts中声明】一致

 

posted @ 2019-11-22 17:57  一封未寄出的信  阅读(527)  评论(0编辑  收藏  举报