Sooraj Bathery
Sooraj Bathery

Reputation: 155

Angular 9 - Property Binding with undefined

I have a component called CustomTextBox

In my CustomTextBox.ts , written as

@Input('id') _id:string
@Input('class') _class:string

In my CustomTextBox.htm, By Using Property Binding, written as

<textarea [id]="_id" [class]="_class"></textarea>

I can able to call the component as any one of the below option from app component

<CustomTextBox></CustomTextBox>
  <CustomTextBox id="sampleid"></CustomTextBox>
  <CustomTextBox class="sampleid"></CustomTextBox>

id and class are optional

But when Called <CustomTextBox></CustomTextBox> Generating the code as below

<CustomTextBox id="undefined" class="undefined"></CustomTextBox>

how can i make property as optional if the values are null or undefined

Stackbitz Solution

https://stackblitz.com/edit/angular-ivy-v1sybw

Upvotes: 1

Views: 3949

Answers (2)

Alexis
Alexis

Reputation: 1784

Try to write this in your template

<textarea [attr.id]="_id?_id:null" [attr.class]="_class?_class:null"></textarea>

This will check if your _id and your _class are set, if not the return value will be null, this will have the effect of removing the attribute and so not showing an undefined value.

Upvotes: 3

charbel
charbel

Reputation: 491

You can add a default value to both your @Input just like any other property:

@Input('id') _id:string = "defaultId";
@Input('class') _class:string = "defaultClass"

When an @input value is undefined it will take the default value.

If you want to completely hide the CustomTextBox in case no _id or _class are provided you can try:

showTextBox: boolean = false;

ngOnInit(): void {
    if(_id !== undefined && _class !== undefined){
         showTextBox= true;
    }
}

and in your html file:

<CustomTextBox *ngIf ="showTextBox"></CustomTextBox>

Upvotes: 1

Related Questions