Javascript 在“角度”视图的子组件中单击按钮时,如何将值设置为“父组件”属性

Javascript 在“角度”视图的子组件中单击按钮时,如何将值设置为“父组件”属性,javascript,angular,angular7,Javascript,Angular,Angular7,我刚接触Angular 7 2+&尝试@Input和@Output。然而,通过@Input将数据从父组件传递到子组件是可以理解的&在适当的位置 然而,另一方面,通过使用@Output概念将数据从子组件传递到父组件是非常基本的&但是实现并不正确 这就是我正在尝试的。在中单击按钮时 子组件,父组件中的属性应为 已转换为大写并显示 ChildComponent.ts import { Component, OnInit, Input, Output, EventEmitter } from '@ang

我刚接触Angular 7 2+&尝试@Input和@Output。然而,通过@Input将数据从父组件传递到子组件是可以理解的&在适当的位置

然而,另一方面,通过使用@Output概念将数据从子组件传递到父组件是非常基本的&但是实现并不正确

这就是我正在尝试的。在中单击按钮时 子组件,父组件中的属性应为 已转换为大写并显示

ChildComponent.ts

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

@Component({
 selector: 'app-child',
 templateUrl: './child.component.html',
})

export class ChildComponent implements OnInit {
@Input('child-name') ChildName: string;
@Output() onHit: EventEmitter<string> = new EventEmitter<string>();

constructor() { }

ngOnInit() {}

handleClick(name): void {
this.onHit.emit(name);
}}
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
 title = 'my-dream-app';
 customerName: string = "";

catchChildEvent(e) {
 console.log(e);
}}
ParentComponent.html

<h1> child works! </h1>
<button (click)="handleClick('eventEmitter')"> Click me! </button>
 <div style="text-align:center">

 <app-child [child-name]="HelloChild"></app-child>

//Trying to bind to Custom event of child component here
<b (onHit)="catchChildEvent($event)"> 
 <i> {{customerName}} </i>
</b>
控制台或绑定中没有错误

从上面的代码片段中,当单击子组件中的按钮时,父组件的属性CustomerName应该获得值&display

示例:

onHit=catchChildEvent$事件应传递给

onHit=catchChildEvent$事件应传递给

您应该将onHit=catchChildEvent$event移动到父html中的app child:

<app-child [child-name]="HelloChild"
    (onHit)="catchChildEvent($event)>
</app-child>
您应该将onHit=catchChildEvent$event移动到父html中的app child:

<app-child [child-name]="HelloChild"
    (onHit)="catchChildEvent($event)>
</app-child>

您正在从应用程序子组件发出事件,因此请附加应用程序子组件的处理程序以使其工作

<div style="text-align:center">

<app-child (onHit)="catchChildEvent($event)" [child-name]="HelloChild"></app-child>

//Trying to bind to Custom event of child component here
<b> 
 <i> {{customerName}} </i>
</b>

您正在从应用程序子组件发出事件,因此请附加应用程序子组件的处理程序以使其工作

<div style="text-align:center">

<app-child (onHit)="catchChildEvent($event)" [child-name]="HelloChild"></app-child>

//Trying to bind to Custom event of child component here
<b> 
 <i> {{customerName}} </i>
</b>