回答:
RxJを使用するSubject
と、親コンポーネントでを宣言しObservable
て子コンポーネントに渡すことができます。子コンポーネントはこれをサブスクライブするだけですObservable
。
親コンポーネント
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
親HTML
<child [events]="eventsSubject.asObservable()"> </child>
子コンポーネント
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
this.eventsSubject.next({data});
に、親this.events.subscribe(({data}) => doSomething(data));
で、次に子で。
eventsSubject
サブジェクトとしてサブスクライブするのではなく、オブザーバブルに変換するのですか?
私の知る限り、これを行うには2つの標準的な方法があります。
1. @入力
親のデータが変更されるたびに、子はngOnChangesメソッドでこれについて通知されます。子供はそれに行動することができます。これは子供と対話する標準的な方法です。
Parent-Component
public inputToChild: Object;
Parent-HTML
<child [data]="inputToChild"> </child>
Child-Component: @Input() data;
ngOnChanges(changes: { [property: string]: SimpleChange }){
// Extract changes to the input property by its name
let change: SimpleChange = changes['data'];
// Whenever the data in the parent changes, this method gets triggered. You
// can act on the changes here. You will have both the previous value and the
// current value here.
}
サービスを作成し、共有サービスでオブザーバブルを使用します。子供はそれをサブスクライブし、変更があるたびに子供に通知されます。これも人気のある方法です。入力として渡すデータ以外のものを送信したい場合、これを使用できます。
SharedService
subject: Subject<Object>;
Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);
Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{
// Whenever the parent emits using the next method, you can receive the data
in here and act on it.})
<child [data]="inputToChild"> </child>
おそらく<child [data]="(inputToChild)"> </child>
変更を取得することになるはずです
親コンポーネントでは、@ ViewChild()を使用して子コンポーネントのメソッド/変数にアクセスできます。
@Component({
selector: 'app-number-parent',
templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
@ViewChild(NumberComponent)
private numberComponent: NumberComponent;
increase() {
this.numberComponent.increaseByOne();
}
decrease() {
this.numberComponent.decreaseByOne();
}
}
更新:
Angular 8以降-
@ViewChild(NumberComponent, { static: false })
numberComponent
ますundefined
。
子コンポーネントで@Input()デコレーターを使用して、親がこの入力にバインドできるようにします。
子コンポーネントでは、それをそのまま宣言します。
@Input() myInputName: myType
プロパティを親から子にバインドするには、バインディングブラケットとそれらの間の入力名をテンプレートに追加する必要があります。
例:
<my-child-component [myChildInputName]="myParentVar"></my-child-component>
ただし、オブジェクトは参照として渡されるため、オブジェクトが子で更新されると、親の変数も更新されることに注意してください。これにより、望ましくない動作が発生する可能性があります。プライマリタイプでは、値がコピーされます。
これをさらに読むには:
ドキュメント:https : //angular.io/docs/ts/latest/cookbook/component-communication.html