1

I want to make a select box component. Simplified components:

@Component({
    moduleId: module.id,
    selector: 'ng2-select',
    template: `
        <div class="container">
           <div class="placeholder"></div>
           <div class="options"
              *ngIf="selectService.isSelectorVisible()"
              [@animateState]="selectService.getSelectorAnimState()">
              <ul>
                 <ng-content></ng-content>
              </ul>
           </div>
        </div>
    `
})
export class SelectComponent {}

@Component({
    moduleId: module.id,
    selector: 'ng2-option',
    template: `
       <li (click)="selectValue($event)" 
           [class.disabled]="disabled"
           [class.active]="value == selectService.getSelectedValue()">
           <div class="inner" #contentWrapper>
               <ng-content></ng-content>
           </div>
       </li>
    `
})
export class OptionComponent {}

I use the component like:

<ng2-select placeholder="Select an option">
   <ng2-option value="1">Option 1</ng2-option>
   <ng2-option value="2" disabled="true">Option 2</ng2-option>
   <ng2-option value="3" selected="true">Option 3</ng2-option>
   <ng2-option value="4">Option 4</ng2-option>
   <ng2-option value="5">Option 5</ng2-option>
</ng2-select>

What I would like to have in my SelectComponent is the information of which option is selected. Problem is that this information is stored within the children of the component and not added to the dom due to *ngIf.

I know that I can do:

  • Pass information of selected option as Input of SelectComponent.
  • Use visibility hidden instead of *ngIf and find it out from ElementRef.

but I don't want to do that this way. I would like to keep it as it is. Is there a way I could find out which of the ng2-option has property selected set to true even if it's not added to the DOM?

Baumi
  • 1,745
  • 1
  • 17
  • 31

1 Answers1

1

These children don't exist, therefore you can't access them.

You can use

[hidden]="!showChildren"

instead of

*ngIf="showChildren"

to get the elements added to the DOM without showing them.

See also What is the equivalent of ngShow and ngHide in Angular2?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Check the points at the bottom of my question. I wrote that I know I can do that this way. My question is more about accessing it on the component life cycle level. I know it's not in the DOM but I was thinking that maybe there is a way of getting content of component template in ngOnInit, etc. – Baumi Aug 25 '16 at 09:14
  • I don't think this is possible. You should rather avoid depending on what's in the DOM and only depend on data in the model and let Angular2 update the DOM according to the model. If the element doesn't exist there is not selected value. – Günter Zöchbauer Aug 25 '16 at 09:18