3

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.

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?
    }
}

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.

generator.component.html snippet

<button type="submit" (click)="clicked(passwordsObj)">Generate</button>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BrianRT
  • 1,952
  • 5
  • 18
  • 27

2 Answers2

2

Use private or public to create an initialize the gs member/property (see the TypeScript Handbook, section Parameter Properties for more information about that):

constructor(private gs: GeneratorService) {}

Then in your click event handler, simply call the service method and pass your passwordsObj as a parameter:

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.

Jean-Philippe Leclerc
  • 6,713
  • 5
  • 43
  • 66
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • I have another question related to http://stackoverflow.com/questions/36109641/angular2-component-one-way-binding-or-input, but don't want to duplicate it (I can't comment on other questions yet). I'm trying to bind user input like ``, but it's not working. I thought that would bind user input to the data source. I don't want to use two way bindings (avoid `[(ngModel)]`). Do I have to use `@Input` for that? – BrianRT Apr 22 '16 at 17:14
  • 1
    @daChi, you should create another question, but if you don't want two-way binding, you probably want ``. – Mark Rajcok Apr 22 '16 at 17:31
0

You could try this:

clicked() {
  this.passwords = gs.generatePasswords(this.passwordsObj);
}

with

<button type="submit" (click)="clicked()">Generate</button>
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360