我是Angular 7
(2岁以上)的新手,并尝试使用@Input
和@Output
。但是,通过@Input将数据从Parent传递到子组件是合理的。
但是,另一方面,通过使用@Output
概念将数据从Child传递到Parent组件非常基本,但是实现方式并不正确。
这是我正在尝试的。在子组件中单击按钮时,父组件中的属性应转换为大写并显示。
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);
}}
ChildComponent.html
<h1> child works! </h1>
<button (click)="handleClick('eventEmitter')"> Click me! </button>
ParentComponent.ts
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
<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>
控制台或绑定中没有错误
从上面的代码片段中,当单击Child Component中的按钮时,父Component的属性CustomerName应该得到值&显示?
您正在从app-child
组件发出事件,因此请附加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>
并且在ts文件中更新cutomerName
属性的值。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
title = 'my-dream-app';
customerName: string = "";
catchChildEvent(e) {
this.customerName = e;
}
}
(onHit)="catchChildEvent($event)"
应该传递给<app-child/>
<app-child [child-name]="HelloChild" (onHit)="catchChildEvent($event)"></app-child>
你应该在父html中将(onHit)="catchChildEvent($event)"
移动到app-child
:
<app-child [child-name]="HelloChild"
(onHit)="catchChildEvent($event)>
</app-child>