Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10844

Component input parameter is received as "undefined" but a value has been specified

I have the following TableMultipleEditComponent in my Angular application:

export class TableMultipleEditComponent implements OnInit {
    @Output() emitMultipleClose: EventEmitter<boolean> = new EventEmitter<
    boolean
    >();
    @Output() emitHoverAndData: EventEmitter<any> = new EventEmitter<any>();

    showBar: boolean;
    @Input()
    table: Table;
    @Input()
    checkedRows;
    @Input()
    recordId: string ;

    ngOnInit() {
        console.log(">> rId-oninit" , this.recordId) ;
        .....
    }
}

And in the html I am passing the [recordId] input value as _INSERT_:

<app-table-multiple-edit
     [table]="table"
     [checkedRows]="checkedRows"
     [recordId]="_INSERT_"
     (emitMultipleClose)="closeSingleRowInsert($event)"
     (emitHoverAndData)="showMultipleEditStatus($event)">
</app-table-multiple-edit>

When I run this in the console I always get >> rId-oninit undefined

I have tried using other values like "-1" and cleaning the cache, as you probably guess that means I am running out of options.

What am I doing wrong ? what can be changing the value between my html and the ngOnInit method

Upvotes: 1

Views: 547

Answers (1)

nash11
nash11

Reputation: 8650

In Angular, when you use [input]="data" in your HTML, data is basically a template expression. Template expressions are similar to JavaScript.

Angular executes the data and assigns it to a property of a binding target, here input. This allows us to dynamically change the value assigned to the input from the component by changing data.

This is similar to interpolation in AngularJS, where in order to display {{data}} in your HTML, data needs to be defined in your controller.

In your case, [recordId]="_INSERT_", recordId is the Input() binding target and _INSERT_ is your template expression. Angular tries to execute this expression but since you have not defined _INSERT_ in your component, it evaluates to undefined.

If you require to pass a constant string to your @Input(), simply pass a string as the expression like so [recordId]="'This is just an example'". If you require it to be dynamic, you should assign a value to _INSERT_ in your component.

Since the template expression is similar to JavaScript, you may even pass a conditional expression if required, [recordId]="recordExists ? '1' : null"

Hope this answers your question.

For more info, here's a reference to the documentation: https://angular.io/guide/template-syntax#template-expressions

Upvotes: 2

Related Questions