我有一個按鈕,它假設將布爾變數從 true 更改為 false,反之亦然,就像一個開關。變數和按鈕在不同的組件中,如果它們不是父子組件,怎么可能共享變數?
uj5u.com熱心網友回復:
所以基本上,組件之間共享三種資料
- @Input, @ViewChild - 當組件是 HTML 模板中的父子時使用這種通信
- @Injectable (services, tokens) - 當組件位于不同的樹中時使用它
- 路由資料 - 這是通過 Router 可用的資料,通常在組件放置在 router-outlet 中時使用
較少使用的技術是
- 使用模板參考,請參閱 如何從父組件中的表單接收值?
- 特殊指令可以訪問共享資料時的中介方法,請參閱NgSwitch
uj5u.com熱心網友回復:
您需要使用服務。此處概述:https ://angular.io/guide/component-interaction
您可以使用一個Subject(無起始值)或一個BehviorSubject(具有起始值)來保存資料,并使用另一個屬性將值公開為Observable組件可以訂閱的值。
例子:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class YourServiceClass {
private _yourValue = new BehaviorSubject<boolean>(false);
yourValue$: Observable<boolean>;
constructor() {
this.yourValue$ = this._yourValue.asObservable();
}
toggleYourValue(): void {
this._yourValue.next(!this._yourValue.getValue());
}
}
然后在您的組件中,您將注入服務并設定訂閱以填充組件上的屬性,該屬性可以在您的代碼中的其他地方使用或系結到模板......
@Component({
selector: 'app-your-component',
template: `Your value is: {{ yourValue }}`
})
export class YourComponent implements OnInit, OnDestroy {
subscription: Subscription;
yourValue: boolean;
constructor(
private readonly yourServiceClass: YourServiceClass,
) {}
ngOnInit(): void {
this.subscription =
this.yourServiceClass.yourValue$.subscribe(yourValue => {
this.yourValue = yourValue;
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533723.html
標籤:有角度的变量网络组件
下一篇:如何在一行之間列印輸入值?
