0

ViewChild works when I specify id like

<div #test_205626>test</div>

But when I do:

<div [attr.id]="test_id">test</div>

I get something like:

<div _ngcontent-gtn-c6="" id="test_205626">test</div>

in output html, but with an error in the same time:

Cannot read property 'nativeElement' of undefined

The code is:

test_id = 'test_205626';
@ViewChild('test_205626', {read: ElementRef, static: false}) private myScrollContainer3: ElementRef;

Why ViewChild doesn't work with [attr.id]?

mr_blond
  • 1,586
  • 2
  • 20
  • 52

1 Answers1

3

From ViewChild's documentation on Angular.io:

The following selectors are supported.

  • Any class with the @Component or @Directive decorator
  • A template reference variable as a string (e.g. query <my-component #cmp></my-component> with @ViewChild('cmp'))
  • Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)
  • Any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)
  • A TemplateRef (e.g. query <ng-template></ng-template> with @ViewChild(TemplateRef) template;)

The id attribute selector that you're trying to use doesn't really work with @ViewChild.

You'll have to stick to using <div #test_205626>test</div> only.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • I need to use *ngFor to display for items in array like `*ngFor="let item of items; let i = index" [attr.id]="i"` And then I planned to get control of some html elements by it's index. Don't angular provide a way for this case? – mr_blond Aug 26 '19 at 07:56
  • And what exactly do you intend to do with that DOM element? Asking because based on your intent, I could suggest something. – SiddAjmera Aug 26 '19 at 13:28
  • My goal is crating instagram like stories blog with infinit scroll. But it will have infinite scroll to top not to bottom how it works on instagram. When user gets to top of the page, few new stories are being added into top of the page. Then I need to scroll down the page to get user back to last story he was reading before new stories were added. Because every stories has different height depend on text amount in it I wanted to get the last story height offset for scrolling down. You can check the prototype on pure js on jsfiddle https://jsfiddle.net/mr_blond97/6fknc3du/ – mr_blond Aug 26 '19 at 13:43