How pass 2 parameters to EventEmitter angular2

十年热恋 提交于 2019-11-30 04:36:29

If you look at the EventEmitter API's emit method, it can only take single parameter of type T

emit(value?: T)

Since only single parameter is allowed, consider passing parameter as in object in emit method. Likewise in below method make & name variable are holding their respective values.

this.addModel.emit({make: make, name: name});
//shorthand is below
this.addModel.emit({make, name});

Another option to strongly type it is as follows:

@Output addModel = new EventEmitter<{make: string, name: string}>();

you can then emit it like @Pankaj-Parkar shows

this.addModel.emit({make, name});
or
this.addModel.emit({make: 'honda', name: 'civic'});

You now have strong typing instead of using object or any.

Adham Amiin

I fixed it by making

EventEmitter<object>();

Then I was able to pass an object such as:

this.MyOutputVariable.emit({ name: 'jack', age: '12' });

And it worked.

I know this is an old Question for me I would create an interface and send it as an object where I can have my code more organized

 export interface addModelArgs{
      make:string,
      name:string
    }
@Output() addModel = new EventEmitter<addModelArgs>();

and call it as following

    this.addModel.emit({make: 'honda', name: 'civic'});
or 
    let savParamters:addModelArgs={make: 'honda', name: 'civic'};

    this.addModel.emit(savParamters);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!