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 運行效果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章