我在 html 文件中有以下 ng 模板
<ng-template #myradio>
<p-radioButton name="test" value="server1" [(ngModel)]="type"></p-radioButton>
<p-radioButton name="test" value="server2" [(ngModel)]="type"></p-radioButton>
<label class="server">Select the server
</ng-template>
在页面加载时,将加载另一个外部组件,单击外部组件按钮,对话框将加载到屏幕上。我想在对话框中插入上面的 ng-template
因此,要附加自定义 onclick 并插入 viewchild,我添加了以下代码,
export TestClass implements AfterViewInit{
@ViewChild('myradio') myradio;
typer= "server1";
ngAfterViewInit(){
document.querySelector('#external-div-element').addEventListener('click', () => {
console.log("attached click");
setTimeout(() => {
document.querySelectorAll('#external-div-element .p-grid')[2].appendChild(myradio);
}, 500);
});
}
}
但是appendchild没有将元素添加到外部对话框中。
这是一个简化的示例,它将模板的内容附加到同一页面中的另一个元素(模拟对话框)。您可以调整代码以在对话框中执行相同的操作:
@Component({
selector: 'app-root',
standalone: true,
template: `
<ng-template #myTemplate>
<div>This content is appended programmatically</div>
</ng-template>
<div #myDialog>
<p>initial dialog content</p>
</div>
<p></p>
<button id="myButton" (click)="onClick()">Append content</button>
`,
})
export class App {
@ViewChild('myTemplate', { read: TemplateRef }) myTemplate!: TemplateRef<any>;
@ViewChild('myDialog', { read: ViewContainerRef }) myDialog!: ViewContainerRef;
constructor() {}
onClick(): void {
const view = this.myTemplate.createEmbeddedView(null);
(this.myDialog.element.nativeElement as HTMLElement).appendChild(view.rootNodes[0]);
}
}
bootstrapApplication(App);