Home  >  Article  >  Web Front-end  >  A brief discussion on 5 methods of communication between Angular components

A brief discussion on 5 methods of communication between Angular components

青灯夜游
青灯夜游forward
2021-08-16 10:04:042643browse

How to communicate between Angular components? The following article will introduce to you 5 methods of communication between Angular components. If necessary, you can refer to it~

A brief discussion on 5 methods of communication between Angular components

Components are built by angular Unit, in order to ensure that data can be transferred back and forth between components in the project, Angular encapsulates some methods that can achieve communication between components. [Related tutorial recommendations: "angular tutorial"]

1. The parent component passes data to the child component through input binding

Parent component

parent.component.ts

age = 18;
name = '  xiaoming '

parent.component.html

<app-child-1 [age]="age" [name]="name"></app-child-1>

Child component

child1.component.ts

@Input() age!: number;

Interception of changes in input attribute values

1. Use an input attribute setter to intercept the parent Changes in value in the component and take action.

child1.component.ts

@Input()
set name(name: string) {
    this._name = name.trim();
}
private _name: string;

2. Use the ngOnChanges() hook function to monitor changes in input attribute values ​​and respond. This method is more appropriate than using property setters when multiple, interactive input properties need to be monitored.

child1.component.ts

ngOnChanges(changes: SimpleChanges): void {
    console.log(changes);
}

We can learn about the related properties of SimpleChange through the type description file officially provided by angular:

A brief discussion on 5 methods of communication between Angular components

A brief discussion on 5 methods of communication between Angular components

2. The parent component listens to the event of the child component and obtains the value passed by the child component to the parent component

The child component exposes an EventEmitter (decorated with @Output (or) attribute. When an event occurs, the child component uses this attribute to emit the event to emit the value to the parent component. The parent component binds to this event property and responds when the event occurs.

Child component

child1.component.ts

@Output() voted = new EventEmitter<boolean>();
emitValue(): void {
    this.voted.emit(true);
}

child1.component.html

<button (click)="emitValue()">Click</button>

Parent component

parent.component.html

<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)"></app-child-1>

parent.component.ts

getChildParam(value: boolean): void {
    console.log(value); // true
}

3. The parent component is read in the template through local variables (#varibleName) Get the properties of the child component and call the method of the child component

Child component

child1.component.ts

address = &#39;Shanghai&#39;;
setAddress(address: string): void {
    this.address = address;
}

Parent Component

parent.component.html

<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)" #child1Component></app-child-1>
<div>{{child1Component.address}}</div>
<button (click)="child1Component.setAddress(&#39;Beijing&#39;)">Click</button>

Limitations: Parent component-child component connections must all be made in the template of the parent component. If the class of the parent component needs to read the property value of the child component or call the method of the child component, it cannot use the local variable method.

4. The parent component calls @ViewChild

When the class of the parent component needs to read the property value of the child component or call the method of the child component, it cannot use local variables. Method; if there is such a need, we can inject the child component into the parent component through @ViewChild;

parent component

parent.component.ts

@ViewChild(Child1Component) private child1Component!: Child1Component;

You can access the properties and methods of child components through the child1Component variable;

5. Use shared services to achieve communication between any components

In order to achieve any For communication between components, we can combine the BehaviorSubject object in Rxjs to create a shared service; for the use of BehaviorSubject, please refer to this blogblog.tcs-y.com/2019/10/08/…

Create dataService.ts

import {BehaviorSubject} from &#39;rxjs&#39;;
import { Injectable} from &#39;@angular/core&#39;;
@Injectable(
  {providedIn: &#39;root&#39;}
)
export class DataService {
  data: BehaviorSubject<number> = new BehaviorSubject<number>(0);
}

Inject the service in the constructor of component 1 and set data

child1.component.ts

constructor(private dataService: DataService) {}
    // 设置data的值
changeData(): void {
    this.dataService.data.next(10);
}

child1.component. html

<button (click)="changeData()">Click</button>

Inject the service in the constructor of component 2 and subscribe to data

child2.component.ts

constructor(private dataService: DataService) {
    this.dataService.data.subscribe(value => {
        console.log(value); // 10
    });
}

For more programming-related knowledge, please visit: Introduction to programming! !

The above is the detailed content of A brief discussion on 5 methods of communication between Angular components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete