2

I have an HTML Div element with angular component children inside the div. Somehow the angular template is like this.

        <mat-radio-group [(ngModel)]="selectedRadioValue">
          <div
            #radioButtonDiv
            *ngFor="let opt of getInputPayload(); index as optIndex"
          >
            <mat-radio-button [value]="opt">
              {{ opt.label }}
            </mat-radio-button>
            <ng-container *ngIf="someCondition === true">
              <app-my-component [attr]="opt.foo"></app-my-component>
            </ng-container>
          </div>
        </mat-radio-group>

I got the outer div element ref using @ViewChildren

  @ViewChildren('radioButtonDiv') radioButtonDiv: QueryList<ElementRef<HTMLDivElement>>;

How do I access the <app-my-component> component class inside radioButtonDiv QueryList?

I tried to use querySelector() from the outer div's nativeElement.

        this.radioButtonDiv.forEach((rbd, index) => {
          if (index === findIndex) {
            // Ignore the setTimeout.
            setTimeout(() => {
              const findChild = rbd.nativeElement.querySelector('app-formulir-medis-attribute');
            }, 500);
          }
        });

However, findChild result in above code showing the nativeElement of <my-component> Component not the Angular component, thus I couldn't access its attributes and properties. How do I get the MyComponent class from the element ref above?

Thank you!

2 Answers 2

0

You can use ContentChild or ng-contetnt tag. here is a stackblitz example.

Sign up to request clarification or add additional context in comments.

Comments

0

To access the <app-my-component> component class rather than the DOM element, you can use @ViewChildren with the component class as the selector.

So, if the component class is MyComponent, it would look like this:

@ViewChildren(MyComponent) myComponents!: QueryList<MyComponent>;

Here's a StackBlitz showing this approach.

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.