Angular コンポーネント間の通信のいくつかの方法を説明します。
Angularコンポーネント間で通信するにはどうすればよいですか?次の記事では、Angular でのコンポーネント通信の方法について説明します。
前回の記事では、 Angular と NG-ZORRO の迅速な開発の組み合わせについて話しました。フロントエンド開発は主にコンポーネントベースの開発であり、コンポーネント間の通信と常に切り離すことができません。では、Angular 開発では、コンポーネント間の通信はどのようなものになるのでしょうか? [関連チュートリアルの推奨事項: "
angular チュートリアル"]
1 つの例から推測すると、この記事は純粋なテキストであり、比較的退屈です。コンソールに表示される内容はあまり役に立たないので、画像は省略します。うーん、読者の皆さんは説明コードに従って理解していただければ幸いです~Vue
と
Reactはマイナーな点で似ています。違い
1. 親コンポーネントは、属性を介して子コンポーネントに値を渡す
これは、プロパティをカスタマイズし、コンポーネントの導入を通じてサブコンポーネントに値を渡すことと同じです。コードを見せてください。
<!-- parent.component.html --> <app-child [parentProp]="'My kid.'"></app-child>
parentProp 属性に名前を付けます。
// child.component.ts import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 输入装饰器 @Input() parentProp!: string; constructor() { } ngOnInit(): void { } }
parentProp を受け入れ、それをページにバックフィルします。
<!-- child.component.html --> <h1>Hello! {{ parentProp }}</h1>
2. 子コンポーネントは、エミッター イベントを通じて親コンポーネントに情報を渡します。
子コンポーネントのデータを、new EventEmitter を通じて親に渡します。 () コンポーネント。
// child.component.ts import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 输出装饰器 @Output() private childSayHi = new EventEmitter() constructor() { } ngOnInit(): void { this.childSayHi.emit('My parents'); } }
emit を通じて親コンポーネントに通知し、親コンポーネントはイベントを監視します。
// parent.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit { public msg:string = '' constructor() { } ngOnInit(): void { } fromChild(data: string) { // 这里使用异步 setTimeout(() => { this.msg = data }, 50) } }
子コンポーネントからのデータを監視した後、
setTimeoutの非同期操作を使用します。これは、サブコンポーネントでの初期化後に
emit を実行したためです。ここでの非同期操作は、
Race Condition 競合エラーを防ぐためです。
fromChild メソッドをコンポーネントに追加する必要があります:
<!-- parent.component.html --> <h1>Hello! {{ msg }}</h1> <app-child (childSayHi)="fromChild($event)"></app-child>
3. 参照を通じて、親コンポーネントはプロパティとメソッドを取得します。子コンポーネントの
参照を操作してサブコンポーネント オブジェクトを取得し、そのプロパティとメソッドにアクセスします。 最初に子コンポーネントのデモ コンテンツを設定します:// child.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 子组件的属性 public childMsg:string = 'Prop: message from child' constructor() { } ngOnInit(): void { } // 子组件方法 public childSayHi(): void { console.log('Method: I am your child.') } }
#childComponent:
<!-- parent.component.html --> <app-child #childComponent></app-child>
ファイルの呼び出し後: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>import { Component, OnInit, ViewChild } from &#39;@angular/core&#39;;
import { ChildComponent } from &#39;./components/child/child.component&#39;;
@Component({
selector: &#39;app-communicate&#39;,
templateUrl: &#39;./communicate.component.html&#39;,
styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit {
@ViewChild(&#39;childComponent&#39;)
childComponent!: ChildComponent;
constructor() { }
ngOnInit(): void {
this.getChildPropAndMethod()
}
getChildPropAndMethod(): void {
setTimeout(() => {
console.log(this.childComponent.childMsg); // Prop: message from child
this.childComponent.childSayHi(); // Method: I am your child.
}, 50)
}
}</pre><div class="contentsignin">ログイン後にコピー</div></div>
このメソッドには制限がありますか? つまり、サブプロパティの修飾子は
protected または
private の場合、エラーが報告されます。サブコンポーネントの修飾子を変更してみてください。エラーの理由は次のとおりです:
protected | |
#private | |
##4. サービスを通じて |
rxjs を使用してデモンストレーションします。
rxjs は、
Observables
rxjs
を記録する記事が後ほどありますので、お楽しみに
次に、親コンポーネントと子コンポーネントで参照し、情報を共有します。まず、
parent-and- という名前のファイルを作成しましょう。子
サービス。// parent-and-child.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; // BehaviorSubject 有实时的作用,获取最新值 @Injectable({ providedIn: 'root' }) export class ParentAndChildService { private subject$: BehaviorSubject<any> = new BehaviorSubject(null) constructor() { } // 将其变成可观察 getMessage(): Observable<any> { return this.subject$.asObservable() } setMessage(msg: string) { this.subject$.next(msg); } }ログイン後にコピー
// parent.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; // 引入服务 import { ParentAndChildService } from 'src/app/services/parent-and-child.service'; import { Subject } from 'rxjs' import { takeUntil } from 'rxjs/operators' @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit, OnDestroy { unsubscribe$: Subject<boolean> = new Subject(); constructor( private readonly parentAndChildService: ParentAndChildService ) { } ngOnInit(): void { this.parentAndChildService.getMessage() .pipe( takeUntil(this.unsubscribe$) ) .subscribe({ next: (msg: any) => { console.log('Parent: ' + msg); // 刚进来打印 Parent: null // 一秒后打印 Parent: Jimmy } }); setTimeout(() => { this.parentAndChildService.setMessage('Jimmy'); }, 1000) } ngOnDestroy() { // 取消订阅 this.unsubscribe$.next(true); this.unsubscribe$.complete(); } }
import { Component, OnInit } from '@angular/core'; import { ParentAndChildService } from 'src/app/services/parent-and-child.service'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { constructor( private parentAndChildService: ParentAndChildService ) { } // 为了更好理解,这里我移除了父组件的 Subject ngOnInit(): void { this.parentAndChildService.getMessage() .subscribe({ next: (msg: any) => { console.log('Child: '+msg); // 刚进来打印 Child: null // 一秒后打印 Child: Jimmy } }) } }
親コンポーネントでは、1 秒後に値を変更します。したがって、親子コンポーネントでは、
msg の初期値 null
が入力されるとすぐに出力され、1 秒後に変更された値Jimmy# が出力されます。 ## が出力されます。同様に、子コンポーネントにサービス情報を指定すると、子コンポーネントが関連する値を出力するときに、親コンポーネントにも出力されます。プログラミング関連の知識について詳しくは、プログラミング入門
をご覧ください。 !
以上がAngular コンポーネント間の通信のいくつかの方法を説明します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Angular.js は、動的アプリケーションを作成するための無料でアクセスできる JavaScript プラットフォームです。 HTML の構文をテンプレート言語として拡張することで、アプリケーションのさまざまな側面を迅速かつ明確に表現できます。 Angular.js は、コードの作成、更新、テストに役立つさまざまなツールを提供します。さらに、ルーティングやフォーム管理などの多くの機能も提供します。このガイドでは、Ubuntu24 に Angular をインストールする方法について説明します。まず、Node.js をインストールする必要があります。 Node.js は、ChromeV8 エンジンに基づく JavaScript 実行環境で、サーバー側で JavaScript コードを実行できます。ウブにいるために

この記事では、Angular のステートマネージャー NgRx について深く理解し、NgRx の使用方法を紹介します。

Angularでモナコエディタを使用するにはどうすればよいですか?以下の記事は、最近業務で使用したangularでのmonaco-editorの使い方を記録したものですので、皆様のお役に立てれば幸いです。

Angular Universal をご存知ですか?これは、Web サイトがより優れた SEO サポートを提供するのに役立ちます。

インターネットの急速な発展に伴い、フロントエンド開発テクノロジーも常に改善され、反復されています。 PHP と Angular は、フロントエンド開発で広く使用されている 2 つのテクノロジーです。 PHP は、フォームの処理、動的ページの生成、アクセス許可の管理などのタスクを処理できるサーバー側スクリプト言語です。 Angular は、単一ページ アプリケーションの開発やコンポーネント化された Web アプリケーションの構築に使用できる JavaScript フレームワークです。この記事では、PHPとAngularをフロントエンド開発に使用する方法と、それらを組み合わせる方法を紹介します。

この記事では、Angular の独立コンポーネント、Angular で独立コンポーネントを作成する方法、および既存のモジュールを独立コンポーネントにインポートする方法について説明します。

Angular フレームワークのコンポーネントのデフォルトの表示動作は、ブロックレベルの要素ではありません。この設計の選択により、コンポーネント スタイルのカプセル化が促進され、開発者が各コンポーネントの表示方法を意識的に定義することが促進されます。 CSS プロパティの表示を明示的に設定することで、Angular コンポーネントの表示を完全に制御して、目的のレイアウトと応答性を実現できます。

Angular プロジェクトが大きすぎます。適切に分割するにはどうすればよいですか?次の記事では、Angular プロジェクトを合理的に分割する方法を紹介します。
