Angular2 将数据传递给点击处理程序
Angular2 passing data to click handler
我不确定我的措辞是否正确; Angular2 发生了很多变化。我正在尝试将表单数据传递给组件的服务。我想在单击 "Generate" 按钮时传递此数据。我将表单数据封装在一个对象中,并希望将该对象传递给注入到组件中的服务。该服务执行所有繁重的工作。该组件真正做的就是显示输出。
generator.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?
}
}
我希望 generatePasswords
方法将 passwordsObj
作为参数。我知道该怎么做。我只是不知道如何在单击组件按钮时触发服务的 generatePasswords
方法。
generator.component.html 片段
<button type="submit" (click)="clicked(passwordsObj)">Generate</button>
你可以试试这个:
clicked() {
this.passwords = gs.generatePasswords(this.passwordsObj);
}
和
<button type="submit" (click)="clicked()">Generate</button>
使用 private
或 public
创建初始化 gs
member/property(有关详细信息,请参阅 TypeScript Handbook 参数属性部分) :
constructor(private gs: GeneratorService) {}
然后在您的点击事件处理程序中,只需调用服务方法并将您的 passwordsObj
作为参数传递:
clicked() {
this.passwords = this.gs.generatePasswords(this.passwordsObj);
}
请注意,您不需要将 passwordsObj
传递给事件处理程序,因为它是组件的 属性,因此 clicked()
方法可以通过this
对象。
我不确定我的措辞是否正确; Angular2 发生了很多变化。我正在尝试将表单数据传递给组件的服务。我想在单击 "Generate" 按钮时传递此数据。我将表单数据封装在一个对象中,并希望将该对象传递给注入到组件中的服务。该服务执行所有繁重的工作。该组件真正做的就是显示输出。
generator.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?
}
}
我希望 generatePasswords
方法将 passwordsObj
作为参数。我知道该怎么做。我只是不知道如何在单击组件按钮时触发服务的 generatePasswords
方法。
generator.component.html 片段
<button type="submit" (click)="clicked(passwordsObj)">Generate</button>
你可以试试这个:
clicked() {
this.passwords = gs.generatePasswords(this.passwordsObj);
}
和
<button type="submit" (click)="clicked()">Generate</button>
使用 private
或 public
创建初始化 gs
member/property(有关详细信息,请参阅 TypeScript Handbook 参数属性部分) :
constructor(private gs: GeneratorService) {}
然后在您的点击事件处理程序中,只需调用服务方法并将您的 passwordsObj
作为参数传递:
clicked() {
this.passwords = this.gs.generatePasswords(this.passwordsObj);
}
请注意,您不需要将 passwordsObj
传递给事件处理程序,因为它是组件的 属性,因此 clicked()
方法可以通过this
对象。