从Angular 2+中的同级组件访问元素

时间:2018-11-13 16:50:26

标签: javascript angular dom angular-components

我有一组可以协同工作的组件。基本上,我正在显示标签列表以及每个标签的数据列表。由于标签窗格可调整大小,因此它成为数据组件的同级对象。即-我的列表组件如下所示:

<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-labelsdata-data都将溢流y设置为自动,因此如果行数超过容器大小,它们可以滚动。两者之间的行数和大小始终相同。我的目标是如果一个容器正在滚动,则两个容器都滚动。因此,我需要将(scroll)事件侦听器附加到两个div(#data-data#labels-labels)上,并更新非滚动元素的滚动值。我的问题是-如何从同级组件中的一个组件访问元素?如果将app-labels嵌入app-data中,那很简单,但是是兄弟姐妹,我看不出该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用@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);
  }


}