Saman Eghbali
Saman Eghbali

Reputation: 79

Set default value for @Input in case that it's null from departure

I have an "attribute" which gets its value form an "object". This "object" is null before user Login, so that "attribute" is null too and Angular CLI wouldn't compile my App.

The Error is:

Error: Template parse errors: Can't bind to 'attribute' since it isn't a known property of 'component'.

Template:

<my-directive [attribute]="object.array.length"></my-directive>

"my-directive" Component:

@Input() attribute: number;

So how can I prevent this error by setting a default value for my Attribute in such case that the Object has not been set. So my Attribute will have a value anyway and my App would compile regardless of Object's Value.

Upvotes: 1

Views: 1330

Answers (3)

gunjit
gunjit

Reputation: 159

You can initialise the input this way:

@Input() attribute: number | null;

So, even if object is null you can initialise the attribute.

Upvotes: 0

ashish.gd
ashish.gd

Reputation: 1768

Use the conditional property ? operator in your template.

Change to:

<my-directive [someAttribute]="someObject?.array.length"></my-directive>

This will tell angular to try and access the array property only when the someObject is available.

Upvotes: 1

Ehsan K. harchegani
Ehsan K. harchegani

Reputation: 3128

You can set default value like this:

@Input() attribute: number=0;

Upvotes: 1

Related Questions