【问题标题】:How to pass data from child to parent?如何将数据从孩子传递给父母?
【发布时间】:2021-10-31 06:23:20
【问题描述】:

我需要将我的子组件中的一个变量传递给父页面。 我试图传递的这个变量,是 Barcode Scanner 的数组结果。

我需要将它传递给父级以发送到 API。

childComponent.ts

this.consultList;

parentComponent.ts

export class ParentComponent implements OnInit {

@Input() consultList: any[] = [];

testCall() {
console.log('Test Consult: ', this.consultList; 
}

【问题讨论】:

  • 你可以使用@Input()@Output()事件来传递变量,从父到子你可以使用@Input()在子组件中定义的变量,从子到父你可以使用事件绑定在子组件中定义@Output。
  • 您好,如果我的回答解决了您的问题,请标记为回答

标签: javascript angularjs typescript ionic-framework


【解决方案1】:

这是一个示例stackblitz 项目,用于测试父子数据传输,使用@Input()@Output()mechanism

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

@Component({
  selector: 'child',
  template: `
    <h1>Hello {{ name }}! This is child component</h1>
    <button (click)="sendEventToParent()">Send data to parent</button>
  `,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `
  ]
})
export class ChildComponent {
  @Input() name: string;
  @Output() eventFromChild: EventEmitter<string> = new EventEmitter();

  sendEventToParent(): void {
    this.eventFromChild.emit('data from child');
  }
}

这里是父组件html,叫做child

<child name="{{ name }}" (eventFromChild)="onEvent($event)"></child>

<h1>This is parent component</h1>
<p>{{dataFromChild}}</p>

和这样的事件绑定

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  dataFromChild = '';

  onEvent(event): void {
    this.dataFromChild = event;
  }
}

【讨论】:

    【解决方案2】:

    你所想的是一个抽象类。抽象类可以像接口一样定义抽象属性,像接口一样定义抽象方法,而与接口不同的是,它可以实际实现方法。你不能初始化一个抽象类,但你可以继承它的代码以便重复使用。

    https://codesandbox.io/s/patient-breeze-h4s3t?file=/src/index.ts

    abstract class Parent {
      abstract someProperty: string;
    
      someCall() {
        console.log(this.someProperty);
      }
    }
    
    class ChildOne extends Parent {
      someProperty = "I am child one";
    }
    
    class ChildTwo extends Parent {
      someProperty = "I am child two";
    }
    
    const one = new ChildOne();
    const two = new ChildTwo();
    
    one.someCall(); // "I am child one";
    two.someCall(); // "I am child two";
    
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2019-04-17
      • 2016-09-12
      • 1970-01-01
      相关资源
      最近更新 更多