Home > Web Front-end > JS Tutorial > Analysis of angular component communication

Analysis of angular component communication

不言
Release: 2018-07-14 09:27:16
Original
1343 people have browsed it

This article mainly introduces the analysis of angular component communication, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.

Single page application component communication has the following This article mainly talks about Angular communication

Analysis of angular component communication

  1. ##Parent component=> Child component

  2. Child Component=> Parent Component

  3. ##Component A = > Component B
##Parent Component=> Child componentChild component=> Parent componentsibling => sibling##@input@outputInject into the parent component##@ViewChild()serviceserviceObservalbe of RxjslocalStorage,sessionStorage

setters (essentially still @input)

ngOnChanges() (deprecated)

# #Local variables




service
Observalbe for Rxjs Observalbe of Rxjs
localStorage,sessionStorage localStorage,sessionStorage

The above chart summarizes the communication solutions that can be used. The last three types in the period are universal. These three types can be used among Angular components. Among them, Rxjs is the most powerful usage, dumping redux. promise, these are also based on functional state management. , let’s talk about them one by one.

Parent component=> Child component

@input, the most commonly used method

@Component({
  selector: 'app-parent',
template: '<p>childText:<app-child></app-child></p>',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  varString: string;
  constructor() { }
  ngOnInit() {
    this.varString = '从父组件传过来的' ;
  }
}
Copy after login
import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<h1>{{textContent}}</h1>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() public textContent: string ;
  constructor() { }
  ngOnInit() {
  }
}
Copy after login

setter

Setter is to intercept the @input attribute. Because when we communicate with components, we often need to process the input attributes, so we need a setter. Setter and getter are often used together. Slightly modify the above child.component.ts
child.component.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<h1>{{textContent}}</h1>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
_textContent:string;
  @Input()
  set textContent(text: string){
   this._textContent = !text: "啥都没有给我" ? text ;
  } ;
  get textContent(){
  return this._textContent;
  }
  constructor() { }
  ngOnInit() {
  }
}
Copy after login

onChange

This is detected through the angular life cycle hook. It is not recommended to use it. If you want to use it, you can Refer to angular documentation

@ViewChild()

@ViewChild() is generally used to call non-private methods of sub-components

           import {Component, OnInit, ViewChild} from '@angular/core';
       import {ViewChildChildComponent} from "../view-child-child/view-child-child.component";
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
      varString: string;
      @ViewChild(ViewChildChildComponent)
      viewChildChildComponent: ViewChildChildComponent;
      constructor() { }
      ngOnInit() {
        this.varString = '从父组件传过来的' ;
      }
      clickEvent(clickEvent: any) {
        console.log(clickEvent);
        this.viewChildChildComponent.myName(clickEvent.value);
      }
    }
Copy after login
      import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-view-child-child',
      templateUrl: './view-child-child.component.html',
      styleUrls: ['./view-child-child.component.css']
    })
    export class ViewChildChildComponent implements OnInit {
      constructor() { }
      name: string;
      myName(name: string) {
          console.log(name);
          this.name = name ;
      }
      ngOnInit() {
      }
    }
Copy after login

Local variables

Local variables Similar to viewChild, it can only be used in html templates. Modify parent.component.html and use the variable #viewChild to represent the subcomponent, and you can call the method of the subcomponent.

<p>
    <input>
    <button>局部变量传值</button>
    <app-view-child-child></app-view-child-child>
            </p>
Copy after login

child component is as follows

@Component({
  selector: 'app-view-child-child',
  templateUrl: './view-child-child.component.html',
  styleUrls: ['./view-child-child.component.css']
})
export class ViewChildChildComponent implements OnInit {

  constructor() { }
  name: string;
  myName(name: string) {
      console.log(name);
      this.name = name ;
  }
  ngOnInit() {
  }

}
Copy after login

Child component=> Parent component

@output()

Output, a common communication, essentially passes a # to the child component ##function, after executing certain methods in the child component, execute the callback function passed in and pass the value to the parent component

parent.component.ts
@Component({
  selector: 'app-child-to-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ChildToParentComponent implements OnInit {

  childName: string;
  childNameForInject: string;
  constructor( ) { }
  ngOnInit() {
  }
  showChildName(name: string) {
    this.childName = name;
  }
}
Copy after login
parent.component. html

<p>
  </p><p>output方式 childText:{{childName}}</p>
  <br>
  <app-output-child></app-output-child>
Copy after login
  child.component.ts
  export class OutputChildComponent implements OnInit {
  // 传入的回调事件
  @Output() public childNameEventEmitter: EventEmitter<any> = new EventEmitter();
  constructor() { }
  ngOnInit() {
  }
  showMyName(value) {
    //这里就执行,父组件传入的函数
    this.childNameEventEmitter.emit(value);
  }
}</any>
Copy after login
Inject parent component

The reason for this principle is that the essential life cycle of parent and child components is the same

export class OutputChildComponent implements OnInit {
  // 注入父组件
  constructor(private childToParentComponent: ChildToParentComponent) { }
  ngOnInit() {
  }
  showMyName(value) {
    this.childToParentComponent.childNameForInject = value;
  }
}
Copy after login
sibling component=> sibling component

service

Rxjs

Communication through service

service in angular is a singleton, so all three communication types can pass through service, and many front-ends understand singletons It’s not very clear, but the essence is

. When you inject a service into a module, all the components of this module can get the properties and methods of this service. They are shared, so you often inject the log service in app.moudule.ts. , http interception service. The service injected in the sub-module can only be shared by this sub-module. The service injected in the component can only be obtained by the sub-component. The following is the service injected into app.module.ts. To demonstrate

user.service.ts
@Injectable()
export class UserService {
  age: number;
  userName: string;
  constructor() { }
}
app.module.ts
@NgModule({
  declarations: [
    AppComponent,
    SiblingAComponent,
    SiblingBComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }
SiblingBComponent.ts
@Component({
  selector: 'app-sibling-b',
  templateUrl: './sibling-b.component.html',
  styleUrls: ['./sibling-b.component.css']
})
export class SiblingBComponent implements OnInit {
  constructor(private userService: UserService) {
    this.userService.userName = "王二";
  }
  ngOnInit() {
  }
}
SiblingAComponent.ts
@Component({
  selector: 'app-sibling-a',
  templateUrl: './sibling-a.component.html',
  styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService) {
  }
  ngOnInit() {
    this.userName = this.userService.userName;
  }
}
Copy after login
Communication through Rx.js

This is the most awesome, this kind of streaming file processing based on subscription publishing. Once subscribed, the source of the publication changes, the subscriber can Get this change; this is not easy to understand. The simple explanation is that b.js, c.js, and d.js subscribe to a certain value change in a.js, and b.js, c.js, and d.js immediately This change was obtained, but a.js did not actively call the methods in b.js, c.js, and d.js. To give a simple example, when each page processes an ajax request, there is a pop-up Prompt information, generally I will put a prompt box component in the template of the

component, which is very cumbersome and has to be done once for each component. If it is based on Rx.js, you can put this in app.component.ts Prompt component, and then app.component.ts subscribes to the public service, which is easier. The code is as follows
First create an album.service.ts

import {Injectable} from "@angular/core";
import {Subject} from "rxjs/Subject";
@Injectable()
export class AlertService {
  private messageSu = new Subject<string>();  //
  messageObserve = this.messageSu.asObservable();
  private  setMessage(message: string) {
    this.messageSu.next(message);
  }
  public success(message: string, callback?: Function) {
    this.setMessage(message);
    callback();
  }
}</string>
Copy after login
sibling-a.component.ts

@Component({
  selector: 'app-sibling-a',
  templateUrl: './sibling-a.component.html',
  styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService, private alertService: AlertService) {
  }
  ngOnInit() {
    this.userName = this.userService.userName;
    // 改变alertService的信息源
    this.alertService.success("初始化成功");
  }
}
Copy after login
app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  message: string;
  constructor(private alertService: AlertService) {
    //订阅alertServcie的message服务
     this.alertService.messageObserve.subscribe((res: any) => {
      this.message = res;
    });
  }
}
Copy after login
So that subscribers can dynamically follow changes in the publishing source

Summary: The above are the commonly used communication methods, and different methods can be adopted in various scenarios.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

The above is the detailed content of Analysis of angular component communication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template