【问题标题】:How can I access the projected DOM before view init?如何在视图初始化之前访问投影的 DOM?
【发布时间】:2017-06-26 18:57:42
【问题描述】:

给定以下组件:

@Component({
  selector: "form-control",
  template: `
    <div class="form-group" #div>
      <label [for]="inputId">{{label}}</label>
      <ng-content></ng-content>
      <small [id]="helpId" class="form-text text-muted">{{help}}</small>
    </div>
  `,
})
export class FormControlComponent {

如何访问调用者提供给&lt;ng-content&gt; 的 DOM 元素以获取其 id(或设置一个,如果 id 未定义)?

我的尝试

我尝试使用 @ViewChild("div"),并在 ngAfterViewInit() 中检查 DOM,并且能够访问输入,但是使用 this.inputId = input.id 将其 id 传播到外部组件导致 ExpressionChangedAfterItHasBeenCheckedError,因为 angular 已经评估inputId.

然后我尝试使用@ContentChild,但不想要求调用者提供模板变量,虽然@ContentChild(NgControl) 匹配指令,但我不知道如何获取该指令的 DOM 元素。

【问题讨论】:

  • 如何使用form-control 组件?显示html

标签: angular


【解决方案1】:

事实证明,如果元素被指令修饰,这真的很容易:

export class FormControlComponent implements AfterContentInit {

  @ContentChild(NgControl, {read: ElementRef}) inputRef: ElementRef;

  ngAfterContentInit() {
    const input = <HTMLInputElement> this.inputRef.nativeElement;
    // do what you want here
  }
}

角度文档确实可以提及read 的允许值:-)

【讨论】:

    猜你喜欢
    • 2023-02-14
    • 2020-12-29
    • 2021-09-10
    • 2020-10-23
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多