angular基础——组件之间通信

一.父子组件通信

1.父组件向子组件传值——@Input

1.父组件html文件
在父组件ts文件中定义好相关变量,在html文件中进行传入

<!-- 通过变量绑定的方式向子组件中传入父组件的变量 -->
<!-- 第二个是父组件中定义的run方法绑定子组件中的变量func -->
<!-- 第三个是传入了父组件对象 -->
<app-header [title]="title" [func]="run" [home]="this"></app-header>

<h1>这里是父组件</h1>

2.子组件ts文件
定义对应的变量进行接收

// 引入Input模块
import { Component, OnInit, Input } from '@angular/core';

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

  // 在子组件中接受父组件传入的参数
  @Input() title:any;
  @Input() func:any;  // 接收传入的方法
  @Input() home:any;  // 接受父组件对象
  constructor() { }

  ngOnInit() {
  }

  getFunc(){
    alert("执行子组件中的方法");
    this.func();  // 子组件执行父组件中的方法
  }
}

3.子组件html文件
在ts文件中接收后,直接在html文件中使用

<h1>这里是子组件,父组件传入的标题是:{{title}}</h1>

<button (click)="getFunc()">在函数中执行传入的父组件方法</button>

2.父组件主动获取子组件中的数据——@ViewChild

1.使用子组件时给子组件定义一个名称

<app-footer #footerChild></app-footer>

2.父组件中引入ViewChild并获取子组件对象

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

@ViewChild('footerChild') footer;

// 通过footer调用子组件中的变量和方法
this.footer.footerRun();

3.子组件通过@Output 触发父组件的方法

1.子组件中引入Output 和EventEmitter

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

// 创建触发器对象
@Output() private outer=new EventEmitter<string>();

// 向外广播数据
sendParent(){
	this.outer.emit('msg from child')
}

2.父组件调用子组件时定义接收事件
outer就是子组件中定义的EventEmitter对象outer

<app-header (outer)="runParent($event)"></app-header>

3.父组件接收到数据会调用自己的runParent 方法,这个时候就能拿到子组件的数据

//接收子组件传递过来的数据
runParent(msg:string){
	alert(msg);
}

二.非父子组件通信

  • 公共的服务
  • Localstorage (推荐)
  • Cookie

参考:https://www.bilibili.com/video/av59049211?from=search&seid=485997827014437418

发布了106 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43667990/article/details/103951096