ある兄弟コンポーネントのクリックイベントを別の兄弟コンポーネントに「聞かれる」ようにしようとしています。
イベントをチェーンの上位で親に渡し、変更を検出してから、何らかの方法で親を介して兄弟(親とは別の子)に渡す必要がありますか?
ページテンプレートのコンポーネント:
<wrap>
<toggler>Toggle the Box</toggler>
<box>Box Content ...</box>
</wrap>
トグラーコンポーネント:
@Component({
selector: 'toggler',
template: `<div (click)="toggleBox()"><ng-content></ng-content></div>`,
})
export class TogglerComponent {
@Output() toggle = new EventEmitter<boolean>();
visible: boolean = false;
toggleBox(): void {
this.visible = !this.visible;
this.toggle.emit(this.visible);
}
}
ボックスコンポーネント:ボックスコンポーネントはどのようにしてトグルイベントを取得できますか?
基本コンポーネント:
@Component({
selector: 'box',
template: `<ng-content *ngIf="toggle"></ng-content>`,
})
export class BoxComponent {
@Input() toggle: boolean;
}
兄弟コンポーネントの通信を実現するには、いくつかの方法があります。
最初のオプションは、公開された監視可能なプロパティを持つサービスを用意し、それをコンポーネントに注入することです。
@Injectable()
export class ToggleService {
private toggle = new Subject<boolean>();
public $toggle = this.toggle.asObservable();
constructor() { }
setToggle(val: boolean){
this.toggle.next(val);
}
}
そこからあなたのコンポーネントは
TogglerComponentexport class TogglerComponent {
constructor(toggleService: ToggleService){}
visible: boolean = false;
toggleBox(): void {
this.visible = !this.visible;
this.toggleService.setToggle(this.visible);
}
}
BoxComponent
export class BoxComponent implements OnInit {
constructor(toggleService: TogglerService){
}
ngOnInit(){
this.toggleService.$toggle.subscribe(val => {
// Do Something
});
}
}
注:このアプローチでは、両方のコンポーネントがサービスの同じインスタンスを共有する必要があるため、DIスコープに注意する必要があります。したがって、プロバイダーは、親コンポーネントか、共有モジュールまたは親モジュールのいずれかにある必要があります。
2番目の方法は、親にプロパティを持ち、それを両方のコンポーネントにバインドすることです。
あなたParentComponent
は何か悪いことになるでしょう
export class ParentComponent implements OnInit {
public toggle: boolean;
constructor() { }
ngOnInit() {
}
changeToggle(val){
this.toggle = val;
}
}
そして、あなたのテンプレートはその関数とプロパティをバインドするだけです
<toggler (toggle)="changeToggle(toggle)"/>
<box [toggle]="toggle"/>
あなたのコメントに基づいて、を使用した別の方法がありますViewChild
。これは次のようになります。
export class ParentComponent implements AfterViewInit {
@ViewChild(TogglerComponent)
togglerComponent: TogglerComponent;
@ViewChild(BoxComponent)
boxComponent: BoxComponent
constructor() { }
ngAfterViewInit() {
this.togglerComponent.toggle
.subscribe(val => this.boxComponent.toggle = val)
}
}
詳細については、https://angular.io/guide/component-interactionを確認してください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加