Angular组件通信

这篇具有很好参考价值的文章主要介绍了Angular组件通信。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1 父传子 @input

  1. 给子组件标签自定义一个属性
<app-life [parentValue]="parentValue" #lifeComponent></app-life>
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 模块
import {Component, Input} from '@angular/core';


@Component({
  selector: 'app-life',
  templateUrl: './life.component.html',
  styleUrls: ['./life.component.scss']
})
export class LifeComponent {
  @Input() parentValue: string;
}

<p>子组件接受父组件的传值:{{ parentValue }}</p>

2 子传父 @ViewChild

父组件:

<app-life [parentValue]="parentValue" #lifeComponent></app-life>
<button (click)="getSonValue()">getSonValue</button>
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)
  }
}

子组件:

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属性和触发事件的方法。

<button (click)="toParentValue()">toParentValue</button>
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属性。

<app-header (outter)="getValueBySonComponent($event)"></app-header>
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

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 如下所示:

<p>app-header接收到的数据:{{ data }}</p>
<button (click)="updateDataFromAppHeader()">app-header发送数据</button>
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 如下所示:

app-component组件发送数据:<input type="text" name="inputValue" [(ngModel)]="inputValue"> <button (click)="send()">发送</button>
<app-header></app-header>
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)
  }

}

Angular组件通信,FE前端相关知识学习,angular.js,javascript,前端文章来源地址https://www.toymoban.com/news/detail-744762.html

到了这里,关于Angular组件通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【HDR学习】HDR视频相关知识讲解(一)

    由来:HDR首先作为静态摄影的一种技术而闻名于世。在静态摄影中,这种进行多次曝光并堆栈成一张暗部和亮部都有细节的图像的方法就是HDR摄影。 随着科技的进步,人们观看影视的体验越来越好,这不仅体现在视频分辨率上,还体现在视频画质上。如今视频的分辨率越来越

    2024年02月11日
    浏览(31)
  • [TS手册学习] 03_函数相关知识点

    TS官方手册:TypeScript: Handbook - The TypeScript Handbook (typescriptlang.org) 函数类型表达式 使用类似于箭头表达式的形式来描述一个函数的类型。 上述代码中, fn: (a:string) = void 表示变量 fn 是一个函数,这个函数有一个参数 a ,是 string 类型,且这个函数的返回值类型为 void ,即没有

    2024年02月05日
    浏览(30)
  • 区块链学习笔记(一)——比特币概念以及密码学相关的知识

    自己做一些让自己读得懂的笔记 1.Bitcoin History In 2008, a person under the pseudonym Satoshi Nakamoto published a paper Bitcoin: A Peer-to-Peer Electronic Cash System . Bitcoin software was released in January 2009 and the mining of the Bitcoin cryptocurrentcy officially started. The genesis block included the “The Times” headline: “ Chan

    2024年02月15日
    浏览(31)
  • 前端之路 | 1.HTML基础必备知识学习篇

    [ 点击 👉 关注「 全栈工程师修炼指南」公众号 ] 设为「⭐️ 星标 」带你从 基础入门 到 全栈实践 再到 放弃学习 ! 涉及 网络安全运维、应用开发、物联网IOT、学习路径 、个人感悟 等知识分享。 希望各位看友多多支持【关注、点赞、评论、收藏、投币】,助力每一个梦想

    2023年04月11日
    浏览(88)
  • 学习javascript,前端知识精讲,助力你轻松掌握

    ✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 所属专栏: 前端泛海 景天的主页: 景天科技苑 JavaScript在1995年诞生了; 由Netscape公司,布兰登·艾奇(Brendan Eich)发明的ECMAScript客户端脚本语言; 主要应用在浏览器,在当时却不温不火. 直到后来Netscape与S

    2024年03月15日
    浏览(53)
  • 大数据相关职位的知识储备与系统学习路线规划以及所需时间

    想要成为一名数据分析师,需要具备以下几个方面的知识储备: 1、数据库知识:掌握 SQL 语言,了解数据表的设计、数据的存储与查询等基本概念 2、统计学知识:包括概率论、统计学、假设检验、方差分析等内容,能够熟练使用统计分析工具进行数据分析。 3、数据挖掘知

    2023年04月10日
    浏览(25)
  • 全栈之前端 | 1.HTML基础必备知识学习篇

    [ 点击 👉 关注「 全栈工程师修炼指南」公众号 ] 设为「⭐️ 星标 」带你从 基础入门 到 全栈实践 再到 放弃学习 ! 涉及 网络安全运维、应用开发、物联网IOT、学习路径 、个人感悟 等知识分享。 希望各位看友多多支持【关注、点赞、评论、收藏、投币】,助力每一个梦想

    2023年04月11日
    浏览(45)
  • 【WEB前端进阶之路】 HTML 全路线学习知识点梳理(中)

    本文是HTML零基础学习系列的第二篇文章,点此阅读 上一篇文章。 标题是通过 h1 - h6 标签进行定义的。 h1 定义最大的标题。 h6 定义最小的标题。浏览器会自动地在标题的前后添加空行,例如: 标题用来正确的显示文章结构 ,通过不同的标题可以为文章建立索引,所以,标题

    2024年02月02日
    浏览(32)
  • 【前端知识】Three 学习日志(十)—— 常见几何体(长方体、球体、圆柱、矩形平面、圆形平面)

    Three 学习日志(十)—— 常见几何体(长方体、球体、圆柱、矩形平面、圆形平面) 一、构建常用几何体 二、 遍历加入场景中 三、效果展示 四、完整代码

    2024年02月07日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包