這是子組件html
<div #hooksContainer style="display: grid;overflow: auto;max-height: 35vh;border: 1px solid black;border-radius: 5px;padding: 10px;">
<!-- Input Var {{inputVar.data}} -->
<ng-content>
<!-- this is space for any content passed from outside -->
</ng-content>
<ng-content select="header">
<!-- this is space for any content passed from outside with tag header-->
</ng-content>
</div>
這是子組件檔案
import { AfterContentChecked, AfterContentInit, ChangeDetectorRef, Component, ContentChild, ElementRef, Input } from '@angular/core';
@Component({
selector: 'app-hook-cycles',
templateUrl: './hook-cycles.component.html',
styleUrls: ['./hook-cycles.component.scss']
})
export class HookCyclesComponent implements AfterContentInit, AfterContentChecked{
@ContentChild("header")
public headerContent!: ElementRef;
@Input()
public inputVar!: { data: string, otherData: { isTrue: boolean, check: string } };
constructor(private cdref: ChangeDetectorRef) {
}
ngAfterContentChecked(): void {
console.log("Content Child headerContent: ", this.headerContent);
}
ngAfterContentInit(): void {
console.log("Content Child headerContent: ", this.headerContent);
}
}
這是應用程式組件的 html 檔案
<div style="padding-top: 25px;">
<h1 style="text-align: center;">App Works!!</h1>
</div>
<app-hook-cycles>something sent from outside<header>[Header] this was too</header></app-hook-cycles>
這是 console.log [consoleLog] 的結果:https ://i.stack.imgur.com/4N1tb.png
第 31 行在 ngAfterContentInit 內
第 27 行在 ngAfterContentChecked 內
uj5u.com熱心網友回復:
根據檔案,不支持原生 HTML 元素作為ContentChild.
在這種情況下,您有兩個選擇:
1.使用模板變數
您可以將模板變數添加到<header>HTML 元素并查詢該變數:
<!-- app.component.html -->
<app-hook-cycles><header #header>...</header></app-hook-cycles>
/** hook-cycles.component.ts **/
@ContentChild("header")
public headerContent!: ElementRef;
見 stackblitz
2.將header包裝成自定義組件
您可以創建自己的<app-header>組件并查詢:
<!-- app.component.html -->
<app-hook-cycles><app-header>...</app-header></app-hook-cycles>
/** hook-cycles.component.ts **/
@ContentChild(HeaderComponent, { read: ElementRef })
public headerContent!: ElementRef;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/437996.html
