I have an implementation where parent wants to pass certain data to child component via the use of @Input
parameter available at the child component. However, this data transfer is a optional thing and the parent may or may not pass it as per the requirement. Is it possible to have optional input parameters in a component. I have described a scenario below:
<parent>
<child [showName]="true"></child> //passing parameter
<child></child> //not willing to passing any parameter
</parent>
//child component definition
@Component {
selector:'app-child',
template:`<h1>Hi Children!</h1>
<span *ngIf="showName">Alex!</span>`
}
export class child {
@Input showName: boolean;
constructor() { }
}
You have two options here.
1) You can use an
*ngIf
on the child in case the child does not need to be displayed when its Input is empty.2) In case the child should get displayed without any input, you can use a modified setter to check for the presence of input variables`
In the child.ts:
Input values are optional by default. Your code will fail only when it tries to access properties of inputs that are not actually passed (since those inputs are
undefined
).You can implement OnChanges or make the input a setter instead of a property to get your code executed when a value is actually passed.
You can use the ( ? ) operator as below
The parent component that uses the child component will be as
LIVE DEMO