In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian for you to introduce in detail "how to communicate between components in Angular", the content is detailed, the steps are clear, the details are handled properly, I hope this article "how to communicate between components in Angular" can help you solve your doubts, the following follows Xiaobian's ideas slowly in depth, together to learn new knowledge.
1. The parent component passes values to the child components through properties
It is equivalent to customizing a property and passing the value to the subcomponent through the introduction of the component. Show you the CODE .
The child component is called in the parent component, where an attribute of parentProp is named.
/ / child.component.tsimport {Component, OnInit, Input} from'@ angular/core';@Component ({selector: 'app-child', templateUrl:'. / child.component.html', styleUrls: ['. / child.component.scss']}) export class ChildComponent implements OnInit {/ / input decorator @ Input () parentPropeller: string; constructor () {} ngOnInit (): void {}}
The child component accepts the variable parentProp passed in by the parent component and backfills it to the page.
Hello! {{parentProp}} 2. The child component passes information to the parent component through the Emitter event
Pass the data of the child component to the parent component through new EventEmitter ().
/ / child.component.tsimport {Component, OnInit, Output, EventEmitter} from'@ angular/core';@Component ({selector: 'app-child', templateUrl:'. / child.component.html', styleUrls: ['. / child.component.scss']}) export class ChildComponent implements OnInit {/ / output decorator @ Output () private childSayHi = new EventEmitter () constructor () {} ngOnInit (): void {this.childSayHi.emit ('My parents');}}
The parent component is notified through emit, and the parent component listens for events.
/ / parent.component.tsimport {Component, OnInit} from'@ angular/core' @ Component ({selector: 'app-communicate', templateUrl:'. / communicate.component.html', styleUrls: ['. / communicate.component.scss']}) export class CommunicateComponent implements OnInit {public msg:string =''constructor () {} ngOnInit (): void {} fromChild (data: string) {/ / Asynchronous setTimeout (() = > {this.msg = data}, 50)}}
In the parent component, after listening on the data from the child component, we use the asynchronous operation of setTimeout. Because we did emit after initialization in the subcomponent, the asynchronous operation here is to prevent Race Condition contention errors.
We also have to add the fromChild method to the component, as follows:
Hello! {{msg}} 3. Through references, the parent component acquires the properties and methods of the child component
We get the subcomponent object by manipulating the reference, and then access its properties and methods.
Let's first set up the demonstration content of the subcomponents:
/ / child.component.tsimport {Component, OnInit} from'@ angular/core' @ Component ({selector: 'app-child', templateUrl:'. / child.component.html', styleUrls: ['. / child.component.scss']}) property of export class ChildComponent implements OnInit {/ / subcomponent public childMsg:string = 'Prop: message from child' constructor () {} ngOnInit (): void {} / / subcomponent method public childSayHi (): void {console.log (' Method: I am your child.')}}
We set the reference ID of the child component # childComponent on the parent component:
Then call the following on the javascript file:
Import {Component, OnInit, ViewChild} from'@ angular/core';import {ChildComponent} from'. / components/child/child.component';@Component ({selector: 'app-communicate', templateUrl:'. / communicate.component.html', styleUrls: ['. / communicate.component.scss']}) export class CommunicateComponent implements OnInit {@ ViewChild ('childComponent') childComponentchild: ChildComponent Constructor () {} ngOnInit (): void {this.getChildPropAndMethod ()} getChildPropAndMethod (): void {setTimeout () = > {console.log (this.childComponent.childMsg); / / Prop: message from child this.childComponent.childSayHi (); / / Method: I am your child. }, 50)}}
The limitation of this method is that the modifier of the child attribute needs to be public, which will report an error when it is protected or private. You can change the modifier of the subcomponent to try. The reasons for reporting errors are as follows:
The type use scope public allows to be called inside and outside the tired, the widest scope protected allows to be used within the class and inherited subclasses, the moderate scope private allows to be used within the class, and the scope is the narrowest 4. Change through service
Let's demonstrate it with rxjs.
Rxjs is a responsive programming library using Observables that makes it easier to write asynchronous or callback-based code.
There will be an article about rxjs in the future. Please look forward to it.
Let's start by creating a service called parent-and-child.
/ / parent-and-child.service.tsimport {Injectable} from'@ angular/core';import {BehaviorSubject, Observable} from 'rxjs' / / BehaviorSubject has a real-time effect. Get the latest value @ Injectable ({providedIn: 'root'}) export class ParentAndChildService {private subject$: BehaviorSubject = new BehaviorSubject (null) constructor () {} / / make it observable getMessage (): Observable {return this.subject$.asObservable ()} setMessage (msg: string) {this.subject$.next (msg);}}
Next, we reference in the parent and child components, whose information is shared.
/ / parent.component.tsimport {Component, OnDestroy, OnInit} from'@ angular/core';// introduces service import {ParentAndChildService} from 'src/app/services/parent-and-child.service';import {Subject} from' rxjs'import {takeUntil} from 'rxjs/operators'@Component ({selector:' app-communicate', templateUrl:'. / communicate.component.html', styleUrls: ['. / communicate.component.scss']}) export class CommunicateComponent implements OnInit, OnDestroy {unsubscribe$: Subject = new Subject () Constructor (private readonly parentAndChildService: ParentAndChildService) {} ngOnInit (): void {this.parentAndChildService.getMessage () .pipe (takeUntil (this.unsubscribe$)) .subscribe ({next: (msg: any) = > {console.log ('Parent:' + msg)) / / print Parent: null / / print Parent: Jimmy}} after one second); setTimeout () = > {this.parentAndChildService.setMessage ('Jimmy');}, 1000)} ngOnDestroy () {/ / unsubscribe to this.unsubscribe$.next (true); this.unsubscribe$.complete ();}} import {Component, OnInit} from' @ angular/core' Import {ParentAndChildService} from 'src/app/services/parent-and-child.service' @ Component ({selector: 'app-child', templateUrl:'. / child.component.html', styleUrls: ['. / child.component.scss']}) export class ChildComponent implements OnInit {constructor (private parentAndChildService: ParentAndChildService) {} / / for better understanding Here I removed the Subject ngOnInit () of the parent component: void {this.parentAndChildService.getMessage () .subscribe ({next: (msg: any) = > {console.log ('Child:' + msg)) / / just came in to print Child: null / / print Child: Jimmy}})} after one second
In the parent component, we change the value after a second. So in the parent-child component, the initial value null of msg is printed as soon as it comes in, and then the changed value Jimmy is printed after a second. Similarly, if you have information about the service in the child component, it will print in the parent component as well as the relevant value in the child component.
After reading this, the article "how to communicate between components in Angular" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.