【问题标题】:Is there any way to find out its parent component's identity/type in a child component level in Angular?有没有办法在 Angular 的子组件级别中找出其父组件的身份/类型?
【发布时间】:2019-10-31 14:09:13
【问题描述】:

说,Angular 中的两个组件之间存在关系:

// Parent component: ParentComponent
// Child component: ChildComponent

// in ParentComponent template
<pp-child></pp-child>

------

export class ChildComponent implements OnInit {
  constructor(
    // wonder if there's something like:
    // private parentRef: HostParentRef
  ) {}
  ngOnInit() {
    console.log(this.parentRef); // This would print ParentComponent
  }
}

我想知道是否有办法在ChildComponent 级别中找出其父组件的type。如果有,在这种情况下我会得到ParentComponent

任何见解将不胜感激!

编辑: 我不是在谈论访问父母的财产或在两者之间进行交流。我只是想知道运行时组件的父组件的type

【问题讨论】:

  • 身份是什么意思?如果您想将任何数据从父组件共享给子组件,您可以将其作为道具传递。如果您能描述您当前的问题是什么,将会很有帮助!
  • @RashiqKodakkad 组件类型我想。在上述情况下,ParentComponent 就是这种情况。
  • @DongBinKim 请示范
  • @shaktimaan 我有,但我没有看到任何与我的问题有关的线索。

标签: angular


【解决方案1】:

您可以通过传递一个参数作为父组件的名称来做到这一点,这样您的子组件就可以知道谁是父组件以及要处理哪些数据

<pp-child [parentInfo]="parentData"> </pp-child>

并将子组件中的输入作为

@Input() parentInfo;
constructor(){
 console.log(parentInfo);
}

您也可以使用此关键字获取父母的信息

<pp-child [parentInfo]="this"> </pp-child>

然后,当您检查 parentInfo 关键字时,您也会获得整个父组件信息。
或者您可以像我们在 javascript 中一样获取元素的父元素,但如果它在 div 中,它将为您提供像 div 这样的直接父元素

【讨论】:

  • 可能,但我想知道是否有其他 Angular 内置注释或用于此目的的东西。
  • 不,据我所知他们不是这样的
  • answer edit 将此用于所有关于父母到孩子的信息
【解决方案2】:

您可以使用eventEmitter

这是一个小例子,可以让您有所了解:

parent.component.ts

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

@Component({
  selector: 'app-parent',
  template: `
    Message: {{message}}
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

child.component.ts

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

@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hola!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

此 URL 将获得一些帮助: https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多