Angular @Input() may or may not have the value

Viewed 1468

I am using @Input() in my component to recieve a value from the parent component.When calling the child component,sometimes there may be value sent to the @Input() and sometimes not.For now I am not getting any error if I am not passing any value to the child component.Is this okay or i should modify the code.

Parent component

<!--THE CHILD DIRECTIVE WITH INPUT-->

<app-child [inputValue]="inputWithValue"></app-child>

<!--THE CHILD DIRECTIVE WITHOUT INPUT-->

<app-child ></app-child>

Child Component

@Input() inputValue :any;

In Brief My question is,

Would there be any problem ,calling the child directive without giving any input? I am not getting any errors for now

2 Answers

You shouldn't receive any errors from Angular. The value will either exist or not.

In the child component just be sure to check the value before using it, simple enough, as errors may occur when you try to interact with that value when it has not been passed in.

@Input() inputValue :any;

public ngOnInit(): void
{
    if (this.inputValue)
    {
        console.log("value passed in, you can use it");
    }
}

same applies for any html, check it exits before trying to display it, could use an *ngIf. This doesnt really apply to a string value but if it was an object. Check the object exists before accessing properties.

<p *ngIf="inputValue">{{ inputValue.someProp }}</p>

If you actually need this input value to render something on your template it will break your specs.

Of course, not all inputs are required, so, if they can be null, just add a ngIf wrapper on your template:

<div *ngIf="input">

</div
Related