0

I want use '@Input()' string for selector, but I can't, the selector always log undefined, here my examples:

Specific example

/********* compA File *********/

// compA -> html (call compB 3 times, every time keying in the different string in [expName])
<compB [expName]="'dog'">
  this is dog //ng-content
</compB>

<compB [expName]="'cat'">
  this is cat //ng-content
</compB>

<compB [expName]="'bird'">
  this is bird //ng-content
</compB>

// compA -> TS
... there is no need, I type string in the html

/********* compB File(it's a template) *********/

// compB -> html
<div #{{expName}}>
    <ng-content></ng-content>
<div>

// compB -> TS
@Input() expName; // when compA using compB, he will type something string to [expName], and compB can read it from @Input.
...

@ViewChild('dog') dog;
@ViewChild('cat') cat;
@ViewChild('bird') bird;

at a lot Input, comA type the dog、cat、bird...to the comB's [expName], so comB use @Input get it, have I look, maybe the [expName] now can be a #cat、#dog、#bird in the html.

ngOnInit(){
    console.log( this.dog );
}

now I try to log #dog, and I failed

Pork Jackson
  • 339
  • 1
  • 15
  • 1
    Can you separate your code by files? Here it looks like your `@Input()` is in the same file as the `@ViewChild`s which of course wouldn't work, it should be in the typescript of the component with selector `comp` – Gilsido Jul 10 '19 at 10:02
  • Hi @Gilsidoo I really had different file(comA、comB), I re-edit my question :( – Pork Jackson Jul 10 '19 at 10:44
  • you can't do it. template variables `#templateVar` are static assets. you can't bind them dynamically. you may have the idea that javascript is an interpreted language and this may work in a js context that's not the case for angular. because angular code goes through a compilation process and such static assets are transformed/compiled to sth else. so you can't do what you are asking for. however, i believe this is an [XY problem](http://xyproblem.info/) you are trying to solve some other problem with this approach and there is a much better approach. just describe your actual problem please. – ysf Jul 10 '19 at 15:52

0 Answers0