繁体   English   中英

无法理解亲子交流

[英]Not able to understand parent child communication

据我所知,对于父子通信,有很多装饰器,例如 @Input、@Output、@ViewChild 和许多其他方法,但是在回答一个问题时,我遇到了下面的问题,现在我无法理解它

App.component.ts(父级)

import { Component } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  parentVariable = 'parentTesting'
  // constructor(private childComp: ChildComponent) {    // Giving error
  //   console.log(this.childComp)  
  // }
}

应用程序组件.html

<h1>Parent</h1>
<child></child>

子组件.ts

import { Component, Input } from '@angular/core';
import { AppComponent } from './app.component';

@Component({
  selector: 'child',
  templateUrl: './child.component.html',
  styles: [`h1 { font-family: Lato; }`]
})
export class ChildComponent  {
  childVariable = 'childTesting'
  constructor(private appComp: AppComponent) {
    console.log(this.appComp)  // This is working
  }
}

在构造函数中的子组件中,我正在获取 AppComponents 实例,但是如果我在 Appcomponent 的构造函数中做同样的事情,则会出现致命错误。

你能告诉我这背后的逻辑吗

这是一个循环引用问题,导致Can't resolve all parameters for ChildComponent: (?). 错误。

这就是为什么:

您正在尝试构造AppComponent ,因此您调用了构造函数

构造函数需要构造ChildComponent再提供,因此现在调用ChildComponent 的构造函数

ChildComponent 的构造函数需要AppComponent即尚未构造(?)参数,等待它完成。

暂无
暂无

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

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