gpt4 book ai didi

javascript - 在 Angular 的子组件中单击按钮时如何将值设置为父组件属性

转载 作者:行者123 更新时间:2023-11-30 07:49:28 26 4
gpt4 key购买 nike

我是 Angular 7(2 岁以上)的新手,正在尝试 @Input@Output。但是,通过@Input 将数据从父组件传递到子组件是可以理解的并已就位。

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

Here is what I am trying. When a button is clicked in the Child component, a property in the parent component should be converted to Upper case & displayed.

子组件.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>

控制台或绑定(bind)没有错误

从上面的代码片段来看,当点击子组件中的按钮时,父组件的属性 CustomerName 应该获取值并显示吗?

示例: https://stackblitz.com/edit/angular-3vgorr

最佳答案

(onHit)="catchChildEvent($event)"应该传递给 <app-child/>

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

关于javascript - 在 Angular 的子组件中单击按钮时如何将值设置为父组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55630889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com