1.父级向子级传值,不管是属性,方法,还是整个父级对象this,都可以通过类似变量的形式传入,具体如下
<app-detail #detail msg="123"></app-detail> //传入的值不是变量 <app-detail #detail [msg]="parentMsg"></app-detail> //传入的是变量 import { Component, OnInit, Input } from '@angular/core'; // 通过input装饰器获取父级传过来的值 @Input() msg: string; //获取值 ngOnInit() { console.log(this.msg, '-----子组件传过来的msg-----'); } //直接 this 可以引用
2.父级获取子组件的信息
第一种可以通过ViewChild的方式进行获取
<app-detail #detail [msg]="parentMsg"></app-detail> //组件 import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core'; //引入 ViewChild @ViewChild('detail') myDom: any; ngAfterViewInit(): void { console.log(this.myDom.msg); this.myDom.run(); } //直接就能获取子组件的数据
第二种通过@Output 和 EventEmitter获取
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; //子组件引入装饰器 @Output() private outer = new EventEmitter(); //定义@Output的装饰器 emitData() { this.outer.emit('传入給父级的值'); } //子组件emit给父级的方法 <button (click)="emitData()">提交数据给父级</button> //按钮触发 <app-detail #detail [msg]="parentMsg" (outer)="getChildMsg($event)"></app-detail> //父级通过outer事件接受,参数是$event, outer必须和子组件定义的变量名一致 getChildMsg(msg) { console.log(msg, '---从子集拿过来的值---'); } // 父级获取emit传过来的值
3.兄弟之间传值通过localStorage或者是服务进行获取