Quote:
On a preliminary understanding of our presents the components and the use of basic, but if all functions into a component inside must appear more redundancy, bloated, we tend to take apart components according to certain rules, after the split components will need to communicate, this article we will come together to meet presents the components in the communication .
Body:
In practical applications, our components will be associated in a tree structure, so the relationship between components is mainly as follows:
- Father and son
- brotherhood
- No direct relation
Prepare our environment:
- To create a
header
Components:ng g c components/header
<app-button></app-button>
<app-title></app-title>
<app-button></app-button>
Copy the code
export class HeaderComponent implements OnInit {
constructor() {}
ngOnInit(): void{}}Copy the code
- To create a
title
Components:ng g c components/title
<span>{{title}}</span>
Copy the code
export class TitleComponent implements OnInit {
public title: string = 'title';
constructor() {}
ngOnInit(): void{}}Copy the code
- To create a
button
Components:ng g c components/button
<button>{{ btnName }}</button>
Copy the code
export class ButtonComponent implements OnInit {
public btnName: string = 'button';
constructor() {}
ngOnInit(): void{}}Copy the code
Direct call
For parent-child components, note that direct calls make parent-child components more coupled, to make clear that direct calls are really required.
-
Mount our header component to our app, so that the parent component relationship between app and header is formed
-
Use # to give our component a name:
-
Now that our header component is empty, let’s expand it, otherwise what to call?
export class HeaderComponent implements OnInit {
public name: string = 'HeaderComponent';
printName(): void {
console.log('component name is'.this.name); }}Copy the code
- Once the component is extended, we can call the properties and functions in the child component header from the parent component app
<app-header #header></app-header>
<p>Invoke child component properties: {{header.name}}<button (click) ="header.printName()">Call child component functions</button>
</p>
Copy the code
-
Step 4 is in the parent component’s HTML template. Sometimes we also need to operate on the child component in the parent component’s TS class, which we will demonstrate next.
-
We need to use a new decorator @viewChild (Component)
export class AppComponent {
title = 'angular-course';
@ViewChild(HeaderComponent)
privateheader! : HeaderComponent;// Declare periodic hooks: called once after component and subcomponent views are updated
ngAfterViewInit(): void {
// Invoke child component properties
console.log(this.header.name);
// Call the subcomponent function
this.header.printName(); }}Copy the code
@ Input and @ the Output
Applies to parent-child components
-
We decouple direct calls in the title component from the extension complications by defining the title in the header component
-
@input () public title: string = ‘title ‘;
-
Add the title property to the header component and assign: public title: string = ‘I am the new title ‘;
-
-
Let’s see the effect now, although the interface is ugly, but the next time to use the component when the title setting is not a little convenient?
-
The parent component’s data is passed to the child component. What about the child component’s data? Let’s implement the following with the @Output() decorator
-
Add the titleChange attribute to the Title component’s ts class: @Output() public titleChange = new EventEmitter();
-
Data is periodically distributed in the TS class of the Title component
ngOnInit(): void {
// Periodically distribute sub-component data
setInterval(() = > {
this.titleChange.emit(this.title);
}, 1500);
}
Copy the code
- Now let’s modify the header parent to receive the sent data:
<app-title
[title] ="title"
(titleChange) ="onChildTitleChange($event)">
</app-title>
Copy the code
onChildTitleChange(value: any) {
console.log('onChildTitleChange: >>', value);
}
Copy the code
Communication using simple benefits of services
Applies to components that are not directly related
- Since we want to communicate through a service, let’s create a service:
ng g s services/EventBus
, and we declare a type ofSubject
To aid communication
@Injectable({
providedIn: 'root',})export class EventBusService {
public eventBus: Subject<any> = new Subject();
constructor(){}}Copy the code
-
We won’t recreate the component for the sake of convenience, because the button and title components in our header fit into components that are not directly related.
-
Modify our Button component and add click events to trigger the triggerEventBus function
export class ButtonComponent implements OnInit {
public btnName: string = 'button';
constructor(public eventBusService: EventBusService) {}
ngOnInit(): void {}
public triggerEventBus(): void {
this.eventBusService.eventBus.next('I'm a button component'); }}Copy the code
- in
title
The acquisition of simulated data in the component
export class TitleComponent implements OnInit {
constructor(public eventBusService: EventBusService) {}
ngOnInit(): void {
this.eventBusService.eventBus.subscribe((value) = > {
console.log(value); }); }}Copy the code
Use cookies, sessions, or localStorage to communicate
-
This is easy enough. Let’s use the title component and the Button component again. This time we’ll save the data in the title component and fetch the data in the Button component. Let’s just show localStorage, everything else is the same.
-
In the title of component ngOnInit () hook holds the title to the localstorage: window. The localstorage. SetItem (‘ title ‘, this title);
-
To get the data in the button component: const title = window. The localStorage. The getItem (” title “);
Conclusion:
This article introduces Component communication in Angular, which ensures that components can communicate properly. So far, components have been used by introducing tags. Are there other ways to use components? Of course, we’ll familiarize ourselves with dynamic components in Angular in the next article.