[英]Angular: Add class to html element inside a CDK Portal
我有一个带有 Angular12 和 Angular Material CDK 的应用程序。
我在 CDK 门户中添加一个模板,模板是这样的:
<ng-template #templatePortalContent>
<div class="editable" #newFormField>
stuff
</div>
</ng-template>
我需要将 class 动态添加到#newFormField
项,但不知道如何访问它。 通常,如果这是一个常规的 ng 模板,例如#addressBlock
我可以使用
@ViewChild('addressBlock') addressBlock: ElementRef;
this.addressBlock.nativeElement.classList.add('editingActive');
但是,这不起作用并引发错误
@ViewChild('newFormField') newFormField: ElementRef;
this.newFormField.nativeElement.classList.add('editingActive');
我认为是因为newFormField
位于插入门户的#templatePortalContent
模板内。
我如何引用内部元素?
该模板将能够从声明它的位置访问组件属性。 渲染模板后,也可以访问ViewChild
(我很确定 👀)
<ng-template #templatePortalContent>
<div [ngClass]="editableClass" #newFormField>
stuff
</div>
</ng-template>
// In the component
public editableClass = 'editable'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.