【发布时间】: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 {
如何访问调用者提供给<ng-content> 的 DOM 元素以获取其 id(或设置一个,如果 id 未定义)?
我的尝试
我尝试使用 @ViewChild("div"),并在 ngAfterViewInit() 中检查 DOM,并且能够访问输入,但是使用 this.inputId = input.id 将其 id 传播到外部组件导致 ExpressionChangedAfterItHasBeenCheckedError,因为 angular 已经评估inputId.
然后我尝试使用@ContentChild,但不想要求调用者提供模板变量,虽然@ContentChild(NgControl) 匹配指令,但我不知道如何获取该指令的 DOM 元素。
【问题讨论】:
-
如何使用
form-control组件?显示html
标签: angular