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 ing from my ngFor
, its an Id
of an item which I want to click (click)="getOrdersFromOrigin(id)"
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 ing from my ngFor
, its an Id
of an item which I want to click (click)="getOrdersFromOrigin(id)"
-
2
id
is part of the scope ofgetOrdersFromOrigin()
so it would not be declared in the scope ofngInInit()
. 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. – GillesC 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. – Manish Commented Dec 6, 2016 at 10:27
-
no I don't know which id i'm going to be clicking, as the ids are ing from
ngFor
and just passing theitem.id
in my function in(click)
event. – MrNew Commented Dec 6, 2016 at 10:27
2 Answers
Reset to default 2You 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
};
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);}
}