0

我有一组协同工作的组件。基本上我正在显示一个标签列表,以及每个标签的数据列表。由于标签窗格是可调整大小的,因此它成为数据组件的兄弟。即-我的列表组件看起来像:

<app-list-labels></app-list-labels>
<app-list-data></app-list-data>

list-labels 和 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-labelsdata-data将overflow-y 设置为auto,以便在行数超过容器大小时它们可以滚动。两者之间的行数和大小始终相同。如果一个容器正在滚动,我的目标是让两个容器都滚动。因此,我需要将一个(scroll)事件侦听器附加到这两个 div (#data-data#labels-labels),并更新非滚动元素的滚动值。我的问题是-如何从同级组件中的一个组件访问元素?如果app-labels嵌入app-data其中将是直截了当的,但作为兄弟姐妹,我不知道该怎么做。

4

1 回答 1

1

您可以尝试使用@Output 装饰器公开 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);
  }


}
于 2018-11-13T17:50:41.240 回答