Angular组件通信

1 父传子 @input

  1. 给子组件标签自定义一个属性
java 复制代码
<app-life [parentValue]="parentValue" #lifeComponent></app-life>
java 复制代码
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public parentValue: string = 'parentValue'
}
  1. 子组件引入 Input 模块
java 复制代码
import {Component, Input} from '@angular/core';


@Component({
  selector: 'app-life',
  templateUrl: './life.component.html',
  styleUrls: ['./life.component.scss']
})
export class LifeComponent {
  @Input() parentValue: string;
}
java 复制代码
<p>子组件接受父组件的传值:{{ parentValue }}</p>

2 子传父 @ViewChild

父组件:

java 复制代码
<app-life [parentValue]="parentValue" #lifeComponent></app-life>
<button (click)="getSonValue()">getSonValue</button>
java 复制代码
import {Component, ViewChild} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public parentValue: string = 'parentValue'
  @ViewChild('lifeComponent') lifeComponent: any

  getSonValue() {
    alert(this.lifeComponent.userName)
  }
}

子组件:

java 复制代码
import {Component, Input} from '@angular/core';
@Component({
  selector: 'app-life',
  templateUrl: './life.component.html',
  styleUrls: ['./life.component.scss']
})
export class LifeComponent {
  public userName: string = 'sonValue'
}

3 output 子传父通信

Angular的Output属性是用于子组件向父组件传递信息的一种方式。通过在子组件中定义一个Output属性,子组件可以通过EventEmitter触发这个属性,父组件可以通过@Output的形式监听子组件的属性,并在属性被触发时调用相应的方法。

在子组件中定义Output属性和触发事件的方法。

java 复制代码
<button (click)="toParentValue()">toParentValue</button>
java 复制代码
import {Component, EventEmitter, Output} from '@angular/core';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent {


  @Output() public outter = new EventEmitter()

  toParentValue() {
    this.outter.emit("i am sonValue")
  }
}

在上面的例子中,我们定义了一个名为outter 的Output属性,并在按钮的点击事件中通过EventEmitter触发了这个属性,并向父组件传递了一个字符串 i am sonValue 。

在父组件中引入子组件,并在模板中使用@Output装饰器监听子组件的Output属性。

java 复制代码
<app-header (outter)="getValueBySonComponent($event)"></app-header>
java 复制代码
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public parentValue: string = 'parentValue'

  getValueBySonComponent(e: any) {
    console.log(e);
  }
}

4 利用公共服务来实现非父子组件通讯

组件间共享一个service服务,那么组件之间就可以通过service实现通信。示例中我们使用rxjs中的BehaviorSubject,它是Subject的一种变体,可以存储最后一条数据或者初始默认值,并会在订阅时发送其当前值。您可以通过RxJS官网进行了解,当然通过文中的说明,您还是可以了解其具体实现的功能。

服务:TransValueService

java 复制代码
import {Injectable} from '@angular/core';

import { BehaviorSubject} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class TransValueService {
  public subject: BehaviorSubject<any> = new BehaviorSubject<any>(0);
  constructor() {
  }
}

两个组件:HeaderComponent AppComponent

HeaderComponent 如下所示:

java 复制代码
<p>app-header接收到的数据:{{ data }}</p>
<button (click)="updateDataFromAppHeader()">app-header发送数据</button>
java 复制代码
import {Component, OnDestroy} from '@angular/core';
import {TransValueService} from "../../services/trans-value.service";
import {Subscription} from "rxjs";

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnDestroy {
  public subscription: Subscription
  public data: string = ''

  constructor(public TransValueService: TransValueService) {
    this.subscription = this.TransValueService.subject.subscribe(data => this.data = data)
  }

  updateDataFromAppHeader() {
    let _data = this.data
    _data += '_zhaoshuai-lc'
    this.TransValueService.subject.next(_data)
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

AppComponent 如下所示:

java 复制代码
app-component组件发送数据:<input type="text" name="inputValue" [(ngModel)]="inputValue"> <button (click)="send()">发送</button>
<app-header></app-header>
java 复制代码
import {Component} from '@angular/core';
import {TransValueService} from "./services/trans-value.service";
import {Subscription} from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public inputValue: string = ''
  public subscription: Subscription

  constructor(public TransValueService: TransValueService) {
    this.subscription = this.TransValueService.subject.subscribe(data => this.inputValue = data)
  }

  send() {
    this.TransValueService.subject.next(this.inputValue)
  }

}
相关推荐
foxhuli22917 分钟前
禁止ifrmare标签上的文件,实现自动下载功能,并且隐藏工具栏
前端
青皮桔1 小时前
CSS实现百分比水柱图
前端·css
失落的多巴胺1 小时前
使用deepseek制作“喝什么奶茶”随机抽签小网页
javascript·css·css3·html5
DataGear1 小时前
如何在DataGear 5.4.1 中快速制作SQL服务端分页的数据表格看板
javascript·数据库·sql·信息可视化·数据分析·echarts·数据可视化
影子信息1 小时前
vue 前端动态导入文件 import.meta.glob
前端·javascript·vue.js
青阳流月1 小时前
1.vue权衡的艺术
前端·vue.js·开源
样子20181 小时前
Vue3 之dialog弹框简单制作
前端·javascript·vue.js·前端框架·ecmascript
kevin_水滴石穿1 小时前
Vue 中报错 TypeError: crypto$2.getRandomValues is not a function
前端·javascript·vue.js
翻滚吧键盘1 小时前
vue文本插值
javascript·vue.js·ecmascript
孤水寒月2 小时前
给自己网站增加一个免费的AI助手,纯HTML
前端·人工智能·html