ViewChild由于 Angular#id從我的 HTML 模板中清理標簽,我無法使用字串參考。
template.html
<div [ngClass]="htmlClass">
<a #inset name="inset" [ngClass]="htmlClass"></a>
</div>
my-component.ts
export class MyComponent extends BaseComponent {
public htmlClass = "dashboard-widget DASHBOARD";
constructor() {
super();
}
base-component.ts
@Injectable()
export abstract class BaseComponent implements AfterViewInit {
@ViewChild('inset') contentInsetView: any;
}
這將導致以下呈現的 HTML:
<div _ngcontent-dkm-c114="" ng-reflect-ng->
<a _ngcontent-dkm-c114="" name="inset" ng-reflect-ng-></a>
</div>
這導致從未設定視圖子項:
ngAfterViewInit() {
console.warn("AfterInit: ", this.contentInsetView);
}
AfterInit: undefined
這段代碼在之前的 Angular 版本(版本 9)中有效,有什么想法嗎?
更新: 添加了似乎導致問題的繼承類。
uj5u.com熱心網友回復:
您需要告訴 angular 它應該從inset.
正確的使用方法@ViewChild是:
@ViewChild('selector', { read: ElementRef }) element?: ElementRef<HTMLElement>
如果我知道選擇器永遠不會消失(不在 a 內*ngIf),我會給 ViewChild 裝飾器static: true和element!: ElementRef<...>.
@ViewChild('selector', { read: ElementRef, static: true }) element!: ElementRef<HTMLElement>
我這樣做是因為這static意味著,當ngOnInit鉤子被觸發時,元素將被定義,并且在任何地方使用它都是最安全的。
uj5u.com熱心網友回復:
發現問題。
為了以 angular 繼承組件,您必須創建另一個帶有 @Component 裝飾器的組件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362691.html
標籤:有角的
