简体   繁体   English

使用@Input组件的父子之间的角向通信不起作用,但没有错误

[英]Angular communication between parent and child using @Input components doesn't work but gives no errors

I am learning about communication between angular components by following this tutorial: 通过学习本教程,我正在学习角度组件之间的通信:

https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/ https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

In my project, I copied the parent component: 在我的项目中,我复制了父组件:

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [childMessage]="parentMessage"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentMessage = "message from parent"
  constructor() {}
}

And the child component: 和子组件:

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

@Component({
  selector: 'app-child',
  template: `
      Say {{ childMessage }}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childMessage: string;

  constructor() { }

}

In app.component.html, I have added the child component tag: 在app.component.html中,我添加了子组件标签:

<app-child></app-child>

This is the result in the browser: 这是浏览器中的结果:
在此处输入图片说明

For some reason, it doesn't display the message value. 由于某种原因,它不显示消息值。
And there's no error in the console. 而且控制台中没有错误。
I don't understand why this is happening. 我不明白为什么会这样。
If you see why, please drop a comment. 如果您知道原因,请发表评论。 Thank you! 谢谢!

Actually you need to call Parent Component to parse your @input to the Child Component . 实际上,您需要调用父组件以将@input解析为子组件 you are directly calling the child selector that is why your not able to displaying anything. 您直接调用子选择器,这就是为什么您无法显示任何内容的原因。

So, call the Parent Component in app.component.html to get input string, 因此,请在app.component.html中调用父组件以获取输入字符串,

<app-parent></app-parent>

You need to update app.component.html to use the parent component instead of the child component and then it will work correctly. 您需要更新app.component.html以使用父组件而不是子组件,然后它才能正常工作。 Example

<app-parent />

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

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