Reputation: 901
While going through an Angular 4 tutorial I found a new way of getting/setting parameter in function.
onValueChange(data?: any)
What does the ?
do?
Upvotes: 2
Views: 6673
Reputation: 6803
It defines optional. Once you define a fucntion/method
like that. You can either pass a value Or Not.
onValueChange(data?: any) {}
can be used as like onValueChange() {}
too. when you have function definition defined like this onValueChange(data?: any) {}
.
Similarly when you can create models In the same manner you can use it too.
For example :
export class YOURCLASS{
ids?: number[];
name :string
}
In this case too you can either have ids array or not but definietly have to have name parameter instead.
Upvotes: 1
Reputation: 232
In JavaScript, every parameter is optional, and users may leave them off as they see fit. When they do, their value is undefined. We can get this functionality in TypeScript by adding a ? to the end of parameters we want to be optional.
So in here, it says you can either pass some values on bound value change event for you van just call the function on event occurrence.
Upvotes: 1
Reputation: 7156
?
sign denotes optional
. Meaning that if you don't pass the value to function, it won't throw an error
.
For example:
This is your function
onValueChange(data?: any) {
console.log(data);
}
onValueChange('somedata'); // will print 'somedata' in the console
onValueChange(); // will print undefined but it won't throw an error
Summary: You can call this function without passing the value as it is optional.
Upvotes: 5
Reputation: 7949
It is an optional parameter.we can pass this parameter or if we don't pass this parameter then it will not give error.We can call function like this:
onValueChange('somedata');
onValueChange();
Upvotes: 1