【问题标题】:Accessing children elements when not added to the DOM due to *ngIf由于 *ngIf 而未添加到 DOM 时访问子元素
【发布时间】:2016-08-25 09:09:41
【问题描述】:

我想做一个选择框组件。简化组件:

@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 {}

我使用这样的组件:

<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>

我希望在我的 SelectComponent 中包含选择了哪个选项的信息。问题是这些信息存储在组件的子组件中,并且由于 *ngIf 而没有添加到 dom 中。

我知道我能做到:

  • 将所选选项的信息作为 SelectComponent 的输入传递。
  • 使用可见性 hidden 代替 *ngIf 并从 ElementRef 中找出它。

但我不想这样做。我想保持原样。有没有办法找出哪个 ng2-option 的属性 selected 设置为 true,即使它没有添加到 DOM 中?

【问题讨论】:

  • 请在您的问题中显示*ngIf
  • 抱歉,不知道我是怎么错过的 ;) 感谢您指出!

标签: angular angular2-directives


【解决方案1】:

这些孩子不存在,因此您无法访问它们。

你可以使用

[hidden]="!showChildren"

而不是

*ngIf="showChildren"

将元素添加到 DOM 中而不显示它们。

另见What is the equivalent of ngShow and ngHide in Angular2?

【讨论】:

  • 检查我问题底部的要点。我写道,我知道我可以这样做。我的问题更多是关于在组件生命周期级别访问它。我知道它不在 DOM 中,但我在想也许有一种方法可以在 ngOnInit 等中获取组件模板的内容。
  • 我认为这是不可能的。您应该避免依赖 DOM 中的内容,而只依赖模型中的数据,让 Angular2 根据模型更新 DOM。如果元素不存在,则没有选定的值。
猜你喜欢
  • 2015-12-01
  • 1970-01-01
  • 2012-05-31
  • 2014-10-27
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
相关资源
最近更新 更多