![](/img/trans.png)
[英]Angular2 : get hold of an element in template of a sibling component from a component
[英]Accessing an element from sibling component in Angular 2+
我有一組可以協同工作的組件。 基本上,我正在顯示標簽列表以及每個標簽的數據列表。 由於標簽窗格可調整大小,因此它成為數據組件的同級對象。 即,我的列表組件如下所示:
<app-list-labels></app-list-labels>
<app-list-data></app-list-data>
列表標簽和列表數據分別如下所示:
// app-list-labels:
<div class="label-header">Labels</div>
<div class="label-labels" id="labels-labels">
<!-- all of my labels looped over and displayed -->
</div>
// app-list-data:
<div class="data-header">Labels</div>
<div class="data-data" id="data-data">
<!-- all of my data rows looped over and displayed -->
</div>
labels-labels
和data-data
都將溢出-y設置為auto,因此如果行數超過容器大小,它們可以滾動。 兩者之間的行數和大小始終相同。 我的目標是如果一個容器正在滾動,則兩個容器都滾動。 因此,我需要將(scroll)
事件偵聽器附加到這兩個div( #data-data
和#labels-labels
),並更新非滾動元素的滾動值。 我的問題是-如何從同級組件中的一個組件訪問元素? 如果將app-labels
嵌入app-data
那將是直接的,但是是兄弟姐妹,我看不到該怎么做。
您可以嘗試使用@Output decoratos公開Div的內容,如下所示:
<app-component-one (divComponent)="divOne = $event"></app-component-one>
<app-component-two (divComponent)="divTwo = $event"></app-component-two>
兄弟1:
import { AfterViewInit, Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
@Component({
selector: 'app-component-one',
templateUrl: './component-one.component.html',
styleUrls: ['./component-one.component.css']
})
export class ComponentOneComponent implements OnInit, AfterViewInit {
@ViewChild('divComponent1') divComponent1: ElementRef;
@Output() divComponent = new EventEmitter();
constructor() {
}
ngOnInit() {
}
ngAfterViewInit(): void {
this.divComponent.emit(this.divComponent1);
}
}
兄弟2:
import { AfterViewInit, Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
@Component({
selector: 'app-component-two',
templateUrl: './component-two.component.html',
styleUrls: ['./component-two.component.css']
})
export class ComponentTwoComponent implements OnInit, AfterViewInit {
@ViewChild('divComponent2') divComponent1: ElementRef;
@Output() divComponent = new EventEmitter();
constructor() {
}
ngOnInit() {
}
ngAfterViewInit(): void {
this.divComponent.emit(this.divComponent1);
}
}
父組件,具有以下組件的同級組件:
import { AfterViewInit, Component, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-component-base',
templateUrl: './component-base.component.html',
styleUrls: ['./component-base.component.css']
})
export class ComponentBaseComponent implements OnInit, AfterViewInit {
divOne: ElementRef;
divTwo: ElementRef;
constructor() {
}
ngOnInit() {
}
ngAfterViewInit(): void {
console.log('div one' , this.divOne);
console.log('div two' , this.divTwo);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.