8 父子传参-子向父传递

1 代码结构

 

 2 myc04.component.html

<p>myc04 works!</p>

<!--emit():触发msgEvent中的函数,就是show()-->
<button (click)="msgEvent.emit('赵云')">Test 1</button>
<button (click)="msgEvent.emit('诸葛亮')">Test 2</button>
<button (click)="msgEvent.emit('关羽')">Test 3</button>
myc04.component.html

3 myc04.component.ts

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

@Component({
  selector: 'app-myc04',
  templateUrl: './myc04.component.html',
  styleUrls: ['./myc04.component.css']
})
export class Myc04Component implements OnInit {
  //生命外部传入的时间,接收此事件
  //output:外传,向外传递消息
  @Output() msgEvent = new EventEmitter();

  constructor() { }

  ngOnInit(): void {
  }

}
myc04.component.ts

 

4 app.component.html

<!-- <app-myc03 name="张三" [age]="20" [boss]="{name:'赵六',age:18,sex:'男'}"></app-myc03>

<app-myc03 name="李四" [age]="19"></app-myc03>

<app-myc03 name="王五" [age]="18"></app-myc03> -->

<!--
    子传父
    1. 子元素不能获取父元素的索引
    2. 父元素需要通过属性的方式传一个方法给子
    3. 子元素再通过这个方法来传递给父元素
-->
<app-myc04 (msgEvent)="show($event)"></app-myc04>
<h1>{{msg}}</h1>
app.component.html

5 app.component.ts

import { Component, ViewChild } from '@angular/core';
import { Myc02Component } from './myc02/myc02.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngPro';

  //查看子组件中#myc02的哪个组件
  //查看子组件中#myc02的哪个组件

  @ViewChild('myc02')
  test!: Myc02Component;
  change() {
    //如何在代码中,拿到子组件的索引
    console.log(this.test)

    //修改abc的name属性
    this.test.name = '你是第一个孩子!!!';
    this.test.age += 10;

    this.test.show();
  }

  msg = '';
  //子向父传参
  //父组件,创建一个间谍:
  //方法:
  show(msg: any) {
    console.log('msg:', msg)
    this.msg = msg;
  }
}
app.component.ts

6 运行效果

 

posted @ 2022-06-14 19:57  孝文  阅读(46)  评论(0)    收藏  举报