Angular コンポーネントはどのように相互作用するのでしょうか?一般的な対話方法の紹介

青灯夜游
リリース: 2021-06-24 11:39:38
転載
1917 人が閲覧しました

コンポーネント間の対話は、主にマスター コンポーネントとスレーブ コンポーネントの間で行われます。では、Angular コンポーネントはどのように相互作用するのでしょうか?次の記事では、Angular コンポーネント間の一般的な対話方法を紹介します。

Angular コンポーネントはどのように相互作用するのでしょうか?一般的な対話方法の紹介

[関連チュートリアルの推奨事項: 「angular チュートリアル」]

1. 入力タイプ Pass によるバインド親コンポーネントから子コンポーネントへのデータ

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. 親コンポーネントは、子コンポーネント

子のイベントをリッスンします。コンポーネント。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>
ログイン後にコピー

Angular コンポーネントはどのように相互作用するのでしょうか?一般的な対話方法の紹介

3. 親コンポーネントと子コンポーネントは ローカル変数を通じて対話します

親コンポーネントはデータ バインディングを使用して子コンポーネントを読み取ることはできませんサブコンポーネントを呼び出すためのプロパティまたはメソッド。ただし、次の例に示すように、親コンポーネント テンプレートに子コンポーネントを表す新しいローカル変数を作成し、この変数を使用して子コンポーネントのプロパティを読み取り、子コンポーネントのメソッドを呼び出すことができます。

サブコンポーネント CountdownTimerComponent カウントダウンし、ゼロに達するとミサイルを発射します。 start メソッドと stop メソッドは、クロックを制御し、テンプレート内のカウントダウン ステータス情報を表示します。

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. 親コンポーネントは <span style="font-size: 16px;">@ViewChild()</span>

を呼び出します。

この ローカル変数 メソッドは簡単で便利なメソッドです。ただし、親コンポーネントと子コンポーネントの接続はすべて親コンポーネントのテンプレートで作成する必要があるため、制限もあります。親コンポーネントのコード自体は、子コンポーネントにアクセスできません。

親コンポーネント クラスがサブコンポーネントのプロパティ値を読み取る必要がある場合、またはサブコンポーネントのメソッドを呼び出す必要がある場合、ローカル変数メソッドは使用できません。

親コンポーネント クラス がこのアクセスを必要とする場合、子コンポーネントを ViewChild として使用し、親コンポーネントに ***inject*** することができます。

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()
  }
}
ログイン後にコピー

プログラミング関連の知識については、プログラミング入門をご覧ください。 !

以上がAngular コンポーネントはどのように相互作用するのでしょうか?一般的な対話方法の紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:csdn.net
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!