typescript Angular2 将数据传递给点击处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36798606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 passing data to click handler
提问by BrianRT
I am not sure if I am phrasing all of this correctly; a lot has changed in Angular2. I am trying to pass form data to a component's service. I want to pass this data whenever the "Generate" button is clicked. I am encapsulating the form data in an object, and want to pass that object to a service that's injected into the component. The service performs all of the heavy lifting. All the component really does is display the output.
我不确定我是否正确地表达了所有这些;Angular2 发生了很多变化。我正在尝试将表单数据传递给组件的服务。每当单击“生成”按钮时,我都想传递此数据。我将表单数据封装在一个对象中,并希望将该对象传递给注入到组件中的服务。该服务执行所有繁重的工作。组件真正做的就是显示输出。
generator.component.ts
生成器.component.ts
export class Generator {
passwords: string[]; // output array
passwordsObj: Object = { // form data passed to service
letters: "",
numbers: "",
symbols: "",
amount: ""
};
constructor(gs: GeneratorService) {
this.passwords = gs.generatePasswords(passwordsObj); // originally hard-coded, I want to now trigger this method when the "Generate" button is clicked
}
clicked(obj) {
// handle the click event?
}
}
I want the generatePasswords
method to take the passwordsObj
as an argument. I know how to do that. I just don't know how to trigger the service's generatePasswords
method when the component's button is clicked.
我希望该generatePasswords
方法将 thepasswordsObj
作为参数。我知道该怎么做。我只是不知道如何在generatePasswords
单击组件的按钮时触发服务的方法。
generator.component.htmlsnippet
generator.component.html片段
<button type="submit" (click)="clicked(passwordsObj)">Generate</button>
采纳答案by Mark Rajcok
Use private
or public
to create an initialize the gs
member/property (see the TypeScript Handbook, section Parameter Properties for more information about that):
使用private
或public
来创建gs
成员/属性的初始化(有关更多信息,请参阅TypeScript 手册,参数属性部分):
constructor(private gs: GeneratorService) {}
Then in your click event handler, simply call the service method and pass your passwordsObj
as a parameter:
然后在您的点击事件处理程序中,只需调用服务方法并将您的passwordsObj
作为参数传递:
clicked() {
this.passwords = this.gs.generatePasswords(this.passwordsObj);
}
Note that you do not need to pass passwordsObj
to the event handler, since it is a property of the component, hence the clicked()
method has access to it via the this
object.
请注意,您不需要传递passwordsObj
给事件处理程序,因为它是组件的属性,因此该clicked()
方法可以通过this
对象访问它。
回答by Thierry Templier
You could try this:
你可以试试这个:
clicked() {
this.passwords = gs.generatePasswords(this.passwordsObj);
}
with
和
<button type="submit" (click)="clicked()">Generate</button>