当父级中单击按钮时如何将数据从子级传递到父级

问题描述 投票:0回答:2

我是角度新手。我有一个大表格。我想让它模块化。这就是为什么我创建了多个较小的子组件以及我在主父组件中使用的所有组件选择器。我在

save
组件中有
parent
按钮,单击“保存”按钮时,应发送表单(子组件)的所有数据以供 api 调用。

我知道如何使用

@Output
将数据从子组件发送到父组件,但我只知道,当我单击子组件中的某个按钮将数据从子组件发送到父组件时, 但就我而言,我的子组件中没有任何按钮。那么有没有什么有效的方法可以达到同样的效果呢?或者我不应该使用这种方法?或者有人在 stackblitz 中有工作示例吗?

提前致谢!

javascript angular typescript
2个回答
1
投票

如果您作为

@Input
传递一个对象(这是一个值为对象的变量,而不是字符串或数字),则无需担心使用@Output,否则您需要制作“某物”来获取孩子们。最简单的方法是在您的孩子中使用模板参考。所以你有,例如

<child-one #childOne ...></child-one>
<child-two #childTwo ...></child-two>
<child-three #childThree ...></child-three>
<button (click)="submit(childOne,childTwo,childThree)">submit</button>

submit(childOne:any,childTwo:any,childThree:any){
   //if, e.g. you has a variable in child-one, child-two and child-three called data you can use
   this.data={dataOne:childOne.data,dataTwo:childTwo.data,dataThree:childThree.data}
   //remember that you can "reach" all the variables public in your children 
   // as, childOne.name_of_variable
}

其他配置,请给我们更多数据:)


0
投票

要处理父组件中的按钮单击并与子组件通信,可以按照以下步骤操作:

  1. 在子组件中声明一个

    @Input
    属性来接收来自父组件的按钮点击状态:

    Child.ts:

    import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent implements OnChanges {
      @Input() isButtonClicked!: boolean;
      list: string[] = ['apple', 'orange', 'banana'];
      @Output() onParentButtonClick = new EventEmitter<string[]>();
    
      ngOnChanges(changes: SimpleChanges): void {
        if (changes['isButtonClicked']) {
          if (this.isButtonClicked) {
            this.sendList();
          }
        }
      }
    
      sendList() {
        this.onParentButtonClick.emit(this.list);
      }
    }
    
  2. 在父组件中定义一个布尔标志来跟踪按钮点击状态:

    Parent.ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent {
      isButtonClicked: boolean = false;
    
      submit() {
        this.isButtonClicked = true;
      }
    
      receiveList(list: string[]) {
        console.log(list);
      }
    }
    
  3. 将布尔标志绑定到子组件并处理子组件发出的事件:

    Parent.html:

    <button (click)="submit()">Click me</button>
    <app-child 
      [isButtonClicked]="isButtonClicked" 
      (onParentButtonClick)="receiveList($event)">
    </app-child>
    

此设置确保当单击父组件中的按钮时,

isButtonClicked
标志设置为
true
,从而触发子组件中的
ngOnChanges
方法。然后子组件将其项目列表返回给父组件,在父组件中可以对其进行适当的处理,如果您想在每次单击后重试获取数据,则需要在每次单击之前将
isButtonClicked
标志设置为
false
按钮。

© www.soinside.com 2019 - 2024. All rights reserved.