Angular 11:如何访问ng模板中的原生元素



我在访问<ng-template>中的元素时遇到问题。它返回undefined.

这是我的演示代码。

.HTML:

<ng-template #enabled>
<div class="form-group">
<div class="ml-4">
<input type="checkbox" id="verifyDetail" #validate class="form-check-input" [(ngModel)]="checkStatus"
[ngModelOptions]="{standalone: true}"
(click)="detailformSubmission(detailForm.valid, $event)"  (blur)="detailformSubmission(detailForm.valid, $event)">
</div>
</div>
</ng-template>

TS:

@ViewChild('validate', {static: true}) vrt!: ElementRef<any>;
ngOnInit(){
console.log(this.vrt);
}

console.log返回undefined.

您可以从装饰器中删除{ static: true}@ViewChild(默认值为false)。之后,您可以实现AfterViewInit接口并使用ngAfterViewInitlifecylce方法,在该方法中,您应该能够从模板.html文件中访问引用。

使用<ng-container>而不是<ng-template>

最新更新