Angular在父视图中呈现子组件
创始人
2024-10-30 20:00:33
0
  1. 子组件内嵌在父组件的模板中

在父组件的模板中直接使用子组件的选择器,将子组件的模板嵌套在父组件的模板中。子组件的内容会被呈现在父组件的模板中。


  

  1. 通过@ViewChild装饰器获取子组件引用

在父组件中通过@ViewChild装饰器来获取子组件的实例,然后将子组件的实例加入到父组件的模板中。父组件就可以显示子组件的内容。

父组件模板:

父组件代码:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})

export class ParentComponent implements AfterViewInit {

  @ViewChild('childContainer', { static: false }) childContainer: ElementRef;

  constructor() {}

  ngAfterViewInit() {
    const childComponent = new ChildComponent();
    childComponent.viewContainerRef = this.childContainer;
    childComponent.ngOnInit();
  }
}

子组件:

import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    
Child component content goes here
` }) export class ChildComponent { constructor() {} viewContainerRef: any; ngOnInit() { this.viewContainerRef.nativeElement.innerHTML = this.template; } get template() { return `
Child component content goes here
`; } }

相关内容

热门资讯

透视辅助!AaPOKER真是存... 透视辅助!AaPOKER真是存在有挂,aapoker真是真的有挂(详细辅助工具存在教程)1、透视辅助...
透视辅助!aapoker安卓版... 1、透视辅助!aapoker安卓版辅助,aa poker辅助软件其实真的有挂(详细有猫腻教程);详细...
透视辅助!wPk辅助软件,wp... 透视辅助!wPk辅助软件,wpk总结一直是有挂(详细有透视辅助教程)1、下载好辅助软件之后点击打开,...
推荐一款!!德扑有挂真是,德扑... 推荐一款!!德扑有挂真是,德扑网上切实有挂(详细平台教程)1、超多福利:超高返利,海量正版游戏,系统...
黑科技辅助!wopoker透明... 黑科技辅助!wopoker透明挂辅助软件,Wepoke德州版本原来是有挂(详细ai辅助教程);1)辅...
wepoke有辅助挂!wepo... wepoke有辅助挂!wepoke辅助机器人,(Wepoke必胜)确实是真的有挂(详细辅助挂教程)1...
透视辅助!Aapoker软件透... 透视辅助!Aapoker软件透明挂,aapoker透明挂本来是有挂(详细辅助教程);1、完成aapo...
透视辅助!wpk微扑克有辅助,... 透视辅助!wpk微扑克有辅助,(wpk规律)切实真的是有挂(详细真的有外卦挂教程)1、许多玩家不知道...
黑科技透明挂!WePoKer确... 黑科技透明挂!WePoKer确实有挂,Wepoke大厅房确实是有挂(详细辅助机器人教程);1、打开软...
第十分钟了解!微扑克辅助挂,微... 第十分钟了解!微扑克辅助挂,微扑克数据都是存在有挂(详细有辅助挂教程);1、让任何用户在无需微扑克辅...