3

Is it possible to trigger a function that has a parameter in it like trigger(id) in ngOnInit?

I have a function that I want to trigger on (click) event as well as in ngOnInit so when the page first load it triggers basically the same function because it calls to the same API end-point.

function to be triggered in ngOnInit

 getOrdersFromOrigin(id: number): void {
   ...
}

so in ngOnInit would be something like this maybe? its showing an error "Cannot find name 'id'"

 ngOnInit() {
    this.getOrdersFromOrigin(id);
  }

Id is coming from my ngFor, its an Id of an item which I want to click (click)="getOrdersFromOrigin(id)"

3
  • 2
    id is part of the scope of getOrdersFromOrigin() so it would not be declared in the scope of ngInInit(). Unless you know which id to call you can't do it, id need to be set or a value need to be used instead. Commented Dec 6, 2016 at 10:17
  • if id in not suppilied to the function it will throw error. You need to handle that in you function if id is not defined or present do something. Because in ngOnInit id might not be available as you are not triggering the click from the view/ its not user triggered. Pass some default value for that if not defined. Commented Dec 6, 2016 at 10:27
  • no I don't know which id i'm going to be clicking, as the ids are coming from ngFor and just passing the item.id in my function in (click) event. Commented Dec 6, 2016 at 10:27

2 Answers 2

2

You can handle it if its in route like param. For example if you are editing some record in table by clicking edit button then your app navigate to edit form you can handle it like this:

import { ActivatedRoute, Params, Router } from '@angular/router';

constructor(
    private route: ActivatedRoute
) { }

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        let id = +params['id']; // (+) converts string 'id' to a number
        this.getOrdersFromOrigin(id);
    });
}

getOrdersFromOrigin(id: number){
//some code
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is the one I need but putting the getOrdersFromOrigin(id) outside the forEach otherwise it'd iterate every time.
0

The param id is in getOrdersFromOrigin(), so it would not work in the scope of ngOnInit(), my suggestion is that you can declare a property id and marked it as @Input(). then you can use it outside. The codes is below:

export class SameComponent implement OnInit {
   @Input() id:number=0; //initialize
    getOrdersFromOrigin(id: number): void {
    ...
  }
  ngOnInit() {   this.getOrdersFromOrigin(id);}
}

1 Comment

But then this will always take the id=0 in the put as default value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.