簡體   English   中英

Angular:將 class 添加到 CDK 門戶內的 html 元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM