【问题标题】:How to pass multiple data back from child to parent component in angular?如何以角度将多个数据从子组件传递回父组件?
【发布时间】:2017-09-01 10:34:32
【问题描述】:

目前,我在学校项目中使用 angular 4。我有一个数组,每一项都是一个可以更新和删除的子组件,这意味着我应该知道索引和数据。

父.ts:

updOne(i:number,stc:string):void{
    this.myarray[i]=stc
}
delete(edu:string):void{
    this.myarray=this.myarray.filter(x=>x!==edu)
}

父.html:

<child-com [edu]=x [num]=i (updstr)="updOne($event)" (delstr)="delete($event)"></child-com>

child-com.ts:

@Input() edu:string
@Input() num:number
@Output() updstr: EventEmitter<string> = new EventEmitter<string>()
@Output() delstr: EventEmitter<string> = new EventEmitter<string>()

//some other code here

save():void{
    this.updstr.emit(this.edu)
    this.updating=false
}
del():void{
    this.delstr.emit(this.edu)
}

delete 效果很好,毫无疑问。问题是更新。其实使用*ngFor,trackBy,全部手动打印,就可以解决这个问题。但我想尝试使用子组件,就像在 React 中一样。当我玩 react 时,我可以只使用 javascript 闭包,即 myfunc.bind(this,i,stc)。

我在这里尝试过使用绑定,没有结果

使用绑定时的代码:
父.ts:

@Output() updstr: EventEmitter<number,string> = new EventEmitter<number,string>()

父.html:

//I've tried some order
//this,i,$event
//$event,this,i
<child-com [edu]=x (updstr)="updOne.bind(this,$event,i)" (delstr)="delete($event)"></child-com>

而且打字稿中的泛型不允许多个数据,所以我不能发出多个数据

所以我的问题是,我如何使用发射或绑定一次将一些数据从子级传递给父级?

【问题讨论】:

  • 只需发送一个包含您的数据的对象:{ testNumber : 1, testString: 'test' }。不过,使用接口比匿名对象更干净。请参阅 angular.io/docs/ts/latest/cookbook/…@Output 示例带有布尔值,但可以是任何类型。
  • 哦,谢谢,现在可以了。但这意味着为函数传递的唯一参数只能是 $event?
  • 是的,它是您键入的对象的 EventEmitter。该对象可以是一切,一个数组,一个包含对象的对象,...

标签: javascript angular typescript


【解决方案1】:

感谢 Alex,使用一个对象可以替代多个数据传递。只是为了确保数据正确,使用了一个接口,有点像这样

export interface Interview{
    num:number
    payload:{
        dt:string
        seeker:string
    }
}

并像使用它

@Output() updstr: EventEmitter<Interview> = new EventEmitter<Interview>()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-24
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多