(精华2020年6月7日更新)Angular基础篇 子组件到父组件传参

父组件主动获取子组件的方法参数

html

<div #myBox>我是一个dom节点</div>
<app-header #header></app-header>
<button type="button" (click)='getChildProp()'>获取子组件header的属性</button>
<button type="button" (click)='getChildMethod()'>获取子组件header的方法</button>

ts

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

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
  //获取Dom
  @ViewChild('myBox')
  public myBoxIn: any;

  @ViewChild('header')
  public header: any;

  constructor() { }

  ngOnInit(): void {
    // console.log(this.myBoxIn)

  }

  //处理dom节点
  ngAfterViewInit() {
    console.log(this.myBoxIn.nativeElement)

    //父组件获取到了整个子组件header
    console.log('父组件获取到了整个子组件header')
    console.log(this.header)
  }
  //获取子组件header的属性
  getChildProp() {
    console.log(this.header.title)

  }
  //获取子组件header的方法
  getChildMethod() {
    console.log(this.header.headRun)
    this.header.headRun();
  }

}

子组件主动触发父组件方法

html


<!-- $event 就是子组件 给父组件的数据,必须是$event -->
<app-footer (outer)='getData($event)'></app-footer>

ts

getData(data){
      console.log(data);
  }

子组件html

<button type="button" (click)='sendParent()'>给父组件Product发射数据</button>

子组件ts

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

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.less']
})
export class FooterComponent implements OnInit {

  @Output() 
  public outer = new EventEmitter();

  constructor() { }

  ngOnInit(): void {

  }
  //给父组件product发射数据
  sendParent(){
    
    this.outer.emit('我是子组件footer的数据')
  }

}

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/106597920