Table of Contents
Component communication
Home Web Front-end JS Tutorial A brief discussion on how to communicate between Angular parent and child components

A brief discussion on how to communicate between Angular parent and child components

Oct 18, 2021 am 10:11 AM
angular Parent-child component communication Component communication

This article will take you to understand the component communication in Angular, and introduce the methods of parent component communicating to child components, and child components communicating to parent components. I hope it will be helpful to everyone!

A brief discussion on how to communicate between Angular parent and child components

Component communication

The component is completely independent, so the data between each other will not be shared. If you want to share data between components, you must Implement communication between components. [Related tutorial recommendations: "angular tutorial"]

Communication between components

  • ##Communication from parent component to child component

  • Subcomponent communicates with parent component

ng6 In order to achieve communication between components, throughput is provided: Input, Output

The parent component communicates with the child component

ng6 is implemented based on ts, so the communication data must define the type (understand the internal structure, allocate memory space)

The parent component communicates with the child component For component communication, the sub-component is the receiver, so the Input throughput is used

The communication from the parent component to the sub-component is divided into 6 steps

The first step In the parent component template, pass data to the child component. If the data is dynamically variable, you can use [] syntax sugar

Second step Define the data model class (if the data is very Simple, you can omit this step)

You can also use the ng directive to define a model class

ng class 类名
Copy after login

Naming convention for model classes: We can define it as a .model.ts file. You can also place the file directly in the models directory and define it as a .ts file

The third step In the sub-component, introduce the model class

The fourth step Step In the subcomponent, introduce the throughput Input

The fifth step There are two ways to receive data through the throughput

  • The first way is to receive data through the Input throughput annotation class

  • @Input() 数据名称: 模型类;
    Copy after login
  • The second way is to receive data through the annotation meta-information inputs of the component

In the annotation class: inputs:

[Attribute data]

In the component:

Attribute data: Model class;

Step 6 Use data. Since the data is added to the component itself, it can be used either in the component or in the template.

Example:

// 4 引入吞吐器
import { Component, OnInit, Input } from '@angular/core';
// 3 引入模型类
import { Data } from '../../models/data';
@Component({
    selector: 'app-inputs',
    templateUrl: './inputs.component.html',
    styleUrls: ['./inputs.component.css'],
    // 5 通过元信息接收
    inputs: ['color', 'data']
})
export class InputsComponent implements OnInit {
    // 5 接收数据
    // @Input() data: Data;
    // @Input() color: string;
    // 声明类型
    data: Data;
    color: string;
    constructor() {
        // 6 组件中使用
        console.log(this)
    }
    ngOnInit() {
    }
}
Copy after login

Communication between child components and parent components

The communication between child components and parent components is based on custom events. For sub-components, it is the publisher, so use the Ouput throughputer

There are six steps to implement communication between sub-components and parent components

The first step In the parent component template, simulate DOM events, bind the parent component method to the child component element, use () syntax sugar

For example (demo)="dealDemo($event)"

In order to pass data, add $event

The second step In the subcomponent, introduce the throughput Output

The third step In the sub-component, introduce the EventEmitter event module

Step 4 There are two ways to create event objects for the sub-component

  • The first way Register through the Output throughputer

  • @Output() 属性名称 = new EventEmitter()
    Copy after login
  • The second type can also be received through the meta-information outputs of the annotation

In the annotation In, register attributes outputs:

[Attribute name]

In component, create event object

Attribute name = new EventEmitter()

Step 5 In the child component, publish the message through the emit method of the event object, and the parameter is the passed data

Step 6 In the parent component, receive it through the parent component method. Data passed by subcomponents

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
    selector: 'app-outputs',
    templateUrl: './outputs.component.html',
    styleUrls: ['./outputs.component.css'],
    // 元信息注册事件对象
    outputs: ['sendMessage']
})
export class OutputsComponent implements OnInit {
    // 4 注册事件对象
    // @Output() sendMessage = new EventEmitter();
    // 实例化
    sendMessage = new EventEmitter();
    constructor() { }
    ngOnInit() {
    }
    // 事件回调函数
    demo() {
        // console.log(111, this)
        // 5 点击按钮的时候,向父组件发布消息
        this.sendMessage.emit({
            msg: 'hello菜鸟',
            color: 'red'
        })
    }
}
Copy after login

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of A brief discussion on how to communicate between Angular parent and child components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

See all articles