0

Example:

outer.html

<div *ngFor="let x of y; let i = index">
        <inner-c></inner-c>
</div>

inner-c.html

<div #bar>
    <div class="row no-gutters mt-3 mb-3 ml-5 mr-5">
        foo
    </div>
</div>

How to get access to #bar DOM element list in outer.component.ts controller? Is that possible?

I tried

@ContentChildren('bar') inputElems: QueryList<ElementRef>; and @ViewChildren('bar') inputElems: QueryList<ElementRef>;

in outer.component.ts but those return an empty list.

1 Answer 1

1

I don't believe you can directly access the elements from other components. You could however set up an event emitter in the child component to emit the ElementRef of the child element. Try the following

inner-c.component.ts

import { Component, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'inner-c',
  templateUrl: './inner-c.component.html',
  styleUrls: ['./inner-c.component.css']
})
export class InnerCComponent {
  @Output() childElement = new EventEmitter();
  @ViewChild('bar')
  set viewChild(list: ElementRef){
    this.childElement.emit(list);
  }

  constructor() {
  }
}

inner-c.component.html

<div #bar>
  <div class="row no-gutters mt-3 mb-3 ml-5 mr-5">
    foo
  </div>
</div>

app.component.ts

export class AppComponent {
  y = [0, 1, 2, 3, 4];

  childElement(event) {
    console.log(event);
  }
}

app.component.html

<div *ngFor="let x of y; let i = index">
  <inner-c (childElement)="childElement($event)"></inner-c>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.