Home  >  Article  >  Web Front-end  >  How do Angular components interact with each other? Introduction to common interaction methods

How do Angular components interact with each other? Introduction to common interaction methods

青灯夜游
青灯夜游forward
2021-06-24 11:39:381943browse

The interaction between components is mainly between master and slave components. So how do Angular components interact with each other? The following article will introduce to you the common interaction methods between Angular components.

How do Angular components interact with each other? Introduction to common interaction methods

[Related tutorial recommendation: "angular tutorial"]

1. Binding through input type Pass data from parent component to child component

child.component.ts

export class ChildComponent implements OnInit {
  @Input() hero: any;
  @Input('master') masterName: string;      // 第二个 @Input 为子组件的属性名 masterName 指定一个别名 master

  constructor() { }

  ngOnInit(): void {
  }

}

child.component.html

<div style="background-color: #749f84">
  <p>child works!</p>
  <h3>{{hero?.name}} says:</h3>
  <p>I, {{hero?.name}}, am at your service, {{masterName}}.</p>
</div>

parent.component.ts

export class ParentComponent implements OnInit {
  hero = {name: &#39;qxj&#39;}
  master = &#39;Master&#39;

  constructor() {
  }

  ngOnInit(): void {
  }

}

parent.component.html

<app-child [hero]="hero" [master]="master"></app-child>

2. The parent component listens to the events of the child component

child.component. ts

export class ChildComponent implements OnInit {
  @Input()  name: string;
  @Output() voted = new EventEmitter<boolean>();
  didVote = false;

  vote(agreed: boolean) {
    this.voted.emit(agreed);
    this.didVote = true;
  }

  constructor() { }

  ngOnInit(): void {
  }

}

child.component.html

<h4>{{name}}</h4>
<button (click)="vote(true)"  [disabled]="didVote">Agree</button>
<button (click)="vote(false)" [disabled]="didVote">Disagree</button>

parent.component.ts

export class ParentComponent implements OnInit {
  agreed = 0
  disagreed = 0
  voters = [&#39;Narco&#39;, &#39;Celeritas&#39;, &#39;Bombasto&#39;]

  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++
  }

  constructor() {
  }

  ngOnInit(): void {
  }

}

parent.component.html

<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<app-child *ngFor="let voter of voters" [name]="voter" (voted)="onVoted($event)"></app-child>

How do Angular components interact with each other? Introduction to common interaction methods

3. Parent component and child component interact through local variables

Parent component cannot use data binding to read child components Properties or methods to call subcomponents. However, you can create a new local variable in the parent component template to represent the child component, and then use this variable to read the properties of the child component and call the method of the child component, as shown in the following example.

Subcomponent CountdownTimerComponent Countdown and launch a missile when it reaches zero. The start and stop methods are responsible for controlling the clock and displaying the countdown status information in the template.

child.component.ts

export class ChildComponent implements OnInit, OnDestroy {
  intervalId = 0
  message = &#39;&#39;
  seconds = 11

  clearTimer() {
    clearInterval(this.intervalId)
  }

  ngOnInit() {
    this.start()
  }

  ngOnDestroy() {
    this.clearTimer()
  }

  start() {
    this.countDown()
  }

  stop() {
    this.clearTimer()
    this.message = `Holding at T-${this.seconds} seconds`
  }

  private countDown() {
    this.clearTimer()
    this.intervalId = window.setInterval(() => {
      this.seconds -= 1
      if (this.seconds === 0) {
        this.message = &#39;Blast off!&#39;
      } else {
        if (this.seconds < 0) {
          this.seconds = 10
        } // reset
        this.message = `T-${this.seconds} seconds and counting`
      }
    }, 1000)
  }

}

child.component.html

<p>{{message}}</p>

parent.component.ts

export class ParentComponent implements OnInit {
  constructor() {
  }
  ngOnInit(): void {
  }
}

parent.component.html

<h3>Countdown to Liftoff (via local variable)</h3>
<button (click)="child.start()">Start</button>
<button (click)="child.stop()">Stop</button>
<div class="seconds">{{child.seconds}}</div>
<app-child #child></app-child>

countdown timer

4. The parent component calls <span style="font-size: 16px;">@ViewChild()</span>

This local variable method is a simple and convenient method. But it also has limitations, because parent component-child component connections must all be made in the template of the parent component. The code of the parent component itself has no access to the child components.

If the class of the parent component needs to read the property value of the subcomponent or call the method of the subcomponent, the local variable method cannot be used.

When the parent component class needs this access, the child component can be used as ViewChild and ***inject*** into the parent component.

countdown-parent.component.ts

import {AfterViewInit, Component, ViewChild} from &#39;@angular/core&#39;
import {ChildComponent} from &#39;../child/child.component&#39;

@Component({
  selector: &#39;app-parent-vc&#39;,
  template: `
    <h3>Countdown to Liftoff (via ViewChild)</h3>
    <button (click)="start()">Start</button>
    <button (click)="stop()">Stop</button>
    <div class="seconds">{{ seconds() }}</div>
    <app-child></app-child>
  `,
})
export class CountdownParentComponent implements AfterViewInit {

  @ViewChild(ChildComponent)
  private timerComponent: ChildComponent

  seconds() {
    return 0
  }

  ngAfterViewInit() {
    // Redefine `seconds()` to get from the `ChildComponent.seconds` ...
    // but wait a tick first to avoid one-time devMode
    // unidirectional-data-flow-violation error
    setTimeout(() => {
      this.seconds = () => this.timerComponent.seconds
    }, 0)
  }

  start() {
    this.timerComponent.start()
  }

  stop() {
    this.timerComponent.stop()
  }
}

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

The above is the detailed content of How do Angular components interact with each other? Introduction to common interaction methods. For more information, please follow other related articles on the PHP Chinese website!

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