Prashant Pimpale
Prashant Pimpale

Reputation: 10697

How to set @Input variable as an optional in angular 5?

I want to set @Input parameters optional.

For example:

Child1.html:

templateUrl:'common-html.html'

Child1.TS:

currentValue : boolean = true;

CASE 2:

Child2.html:

templateUrl:'common-html.html'

Child2.TS:

// Not declared **currentValue**

Common-HTML.html:

<app-master [isLogEnabled]="currentValue"></app-master>

But above changes giving an error while AOT:

Property 'isLogEnabled' does not exist on type Child2.Component

So I cannot change HTML of :

<app-master [isLogEnabled]="currentValue"></app-master>

Upvotes: 0

Views: 2609

Answers (2)

Roman Leliuk
Roman Leliuk

Reputation: 91

You can't provide property that you didn't declare. But you can use something like this:

<app-master [isLogEnabled]="currentValue || false"></app-master>

Or inside component you can create getter:

get isLogEnabled() {
    return this.isLogEnabled || false;
}

Or you can try to use '?'

@Input() isLogEnabled?: boolean;

Upvotes: 0

AliF50
AliF50

Reputation: 18809

I would do:

App-Master-Component.ts

@Input() isLogEnabled: boolean = false; // can change false to true, null or w.e. depending on what you want as the default
// if consumer passes in a value, it will be overridden

Then in Child2.component.html

<app-master></app-master>

You cannot bind [isLogEnabled]="currentValue" if currentValue does not exist in the Child2.component.ts file.

Upvotes: 1

Related Questions