繁体   English   中英

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

[英]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-labelsdata-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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM