简体   繁体   English

如何访问 Angular 6 中其他组件中的 DOM 元素?

[英]How to access DOM element in other component in Angular 6?

I have two components header & a.我有两个组件标题和一个。 In header component there is a hidden element and I want to show it from component a, but I don't know how do I do this.在标头组件中有一个隐藏元素,我想从组件 a 中显示它,但我不知道该怎么做。

header.component.html header.component.html

<p>
  header works!
</p>
<div #hidden_element style="display: none">
  <h1>Hidden Element in header</h1>
</div>

a.component.html a.组件.html

<div (click)="show()">Show</div>

a.component.ts a.组件.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {

  constructor() { }
  show() {
    // code to display hidden element in header component
  }
  ngOnInit() {
  }

}

app.component.html应用程序组件.html

<app-header></app-header>
<app-a></app-a>

You can do it by sending events between directives via a custom service.您可以通过自定义服务在指令之间发送事件来实现。 A simple example would look something like this:一个简单的例子看起来像这样:

// my-service.component.ts
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/index";

@Injectable()
export default class MyService {

    private messageSource = new Subject<string>();

    listener = this.messageSource.asObservable();

    send(message: string): void {
        this.messageSource.next(message);
    }
}

Your 'a' component will look something like this:您的“a”组件将如下所示:

// a.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {

  constructor(private myService: MyService) { }

  show() {
    // code to display hidden element in header component
    this.myService.send('some message');
  }
  ngOnInit() {
  }

}

and this is your header component:这是您的标头组件:

// header.component.ts
@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: []
})
export class HeaderComponent implements OnDestroy {

    private serviceSubscription: Subscription;

    constructor(private myService: MyService) { 
        this.serviceSubscription = this.myService.listener.subscribe(message => {
            // TODO: Do whatever you want to do here to show the hidden element
        });
    }

    ngOnDestroy(): void {
        this.serviceSubscription.unsubscribe();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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