三、父子之间传值

23 阅读1分钟

一、 父组件向子组件传值

1.父组件自定义一个属性

 <app-self-child [num]="num"></app-self-child>

2.子组件 Input 此属性

 import {  Input } from '@angular/core';
 
export class HelloSelfChild implements OnInit {
   constructor() { }
       
   ngOnInit() { }
 

   @Input() num:number;
}
  • 如果有变量重名
  @Input('num') myNum:number;

二、 子组件向父组件传值:通过一个函数

1.在父组件中自定义事件

  <app-self-child (myClick)="add()"></app-self-child>
  • 注意如果要传参 父组件自定义事件必须要有一个 $event
 <app-self-child (myClick)="add($event)"></app-self-child>

2.在子组件中子组件通过事件发射器向父组件传递数据:

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

@Component({
    selector: 'app-self-child',
    template: `
    <hr>
    <button (click)="childAdd()">子组件btn</button>
    `
})

export class HelloSelfChild implements OnInit {
    constructor() { }

    ngOnInit() { }
    @Output() myClick = new EventEmitter<string>(); //子组件向父组件传递事件
    childAdd(){
        this.myClick.emit();
    }
}

三子组件监听父组件传值的变化

通过 class中的getter 和 setter来监听父组件传值的变化

  private _num: number;
    @Input()
    set num(value: number) {
        console.log('开始设置了')
        this._num = value;
    }
    get num(): number {
        console.log('num', this._num)
        return this._num;
    }
}

四父组件通过本地变量调用子组件方法(vue中的ref传值)

 <app-self-child [num]="num" #child></app-self-child>
   <button (click)="child.chagegeNum(11)">调用子组件中的方法</button>
    age: number;
    chagegeNum(age:number) {
        this.age = age
    }

五通过@ViewChild

import { Component, OnInit,ViewChild } from '@angular/core';
import {HelloSelfChild} from './hello-self-child.component'
@Component({
    selector: 'app-hello-self-event',
    template: `
 
    <app-self-child [num]="num" #child></app-self-child>
   <button (click)="child.chagegeNum(11)">调用子组件中的方法</button>
   <button (click)="viewChild()">使用ViewChild</button>
    `
})

export class HelloSelfEventComponent implements OnInit {
    count = 0;
    num = 100;
    constructor() { }

    ngOnInit() { }
    add(){
        this.count++;
    }

    @ViewChild(HelloSelfChild)
    private child:HelloSelfChild;
    viewChild(){
       this.child.chagegeNum(12) 
    }
}