Reputation: 9900
I am experimenting with Angular 8 and passing data between components.
The child component is as follows:
import { Component, OnInit, Input } from '@angular/core';
import { SelectService } from '../select.service';
@Component({
selector: 'app-dynamic-selects, test-dynamic-tag',
templateUrl: './dynamic-selects.component.html',
styleUrls: ['./dynamic-selects.component.css']
})
export class DynamicSelectComponent implements OnInit {
@Input() id: any;
options: any[];
constructor(private selector: SelectService) { }
ngOnInit() {
console.log("TESTING INPUT VALUE: " + this.id);
console.log(this.id);
this.selector.users().subscribe(users => {
this.options = users;
});
}
}
The parent template is where the problem is being manifested. I am attempting to output different examples of the child component tag but only the component tags where [id] is an integer are being output. Tags with strings just say 'undefined'.
@Input() id is typed as any but even typing is as string does not resolve the issue.
Below is the parent component markup:
<app-dynamic-selects [id]="7"></app-dynamic-selects>
<br><br>
<test-dynamic-tag [id]="test"></test-dynamic-tag>
<br><br>
<app-dynamic-selects [id]="Batman"></app-dynamic-selects>
<br><br>
<test-dynamic-tag [id]="14"></test-dynamic-tag>
As shown above, I am using 2 different selector tags for the same component. But it doesn't matter which I use, subsequent tags print out undefined.
Here is what is printed in my console area from the html above:
TESTING INPUT VALUE: 7
7
TESTING INPUT VALUE: undefined
undefined
TESTING INPUT VALUE: undefined
undefined
TESTING INPUT VALUE: 14
14
Why do I get undefined rather than the output, string or integer, that I expect?
Upvotes: 0
Views: 451
Reputation: 765
to complete the response of Markus Dresch, you can use either
<test-dynamic-tag [id]="test"></test-dynamic-tag>
and then you should have a variable named test
in you rcontroller
or
<test-dynamic-tag id="test"></test-dynamic-tag>
and then you pass a String value to your child component
Upvotes: 1
Reputation: 5574
When using bracket syntax, you are binding to a expression, typically a property in your component. A number literal is a valid expression, so the binding works. test
and Batman
is not a valid expression if there's no property of that name defined in your component. 'test'
and 'Batman'
would work, since a string literal is a valid expression.
When binding to literals, you don't really need the bracket syntax though, simply use the normal html attribute syntax (i.e. without brackets).
Upvotes: 3