显示父零部件中的子零部件

  • 本文关键字:零部件 显示 angular
  • 更新时间 :
  • 英文 :


我想在显示父组件后立即在父组件中显示我的子组件。但我真的不知道我错过了什么

我的子组件

<ng-template #template let-modal >
<div class="row">
<div class="col-lg-12 align-evenly">
<button class="btn btn-primary btn-rounded right-margin">Monthly</button>
<button class="btn btn-primary btn-rounded right-margin">Quaterly</button>
</div>
</div>
</ng-template> 

父组件在ts文件中有我的子组件

@ViewChild(MyChildComponent) childComponent: MyChildComponent; 

Parent html有一个div,我想在其中显示子按钮

<div class="row" *ngIf="childComponent">
</div>    

请帮助

与johnpeters非常相似,我将给您另一个例子,说明我如何在一个应用程序中解决它。

目标:在父页面中显示子组件

要执行的操作:
在应用程序内部创建文件夹'parent',
内部'parent'create folder'components',
parent'内部创建组件'parent-page.component',
内部'组件'创建组件'child.component,
parent内部创建文件'parent.module.ts',

将组件导入该模块并导出父页面。

创建这个文件夹和组件结构后,让我们看看代码:

// parent.module.ts
@NgModule({
declarations: [
ParentPageComponent,
ChildComponent
],
imports: [
// import modules if you need here like UtilsModule, MaterialModule etc..
],
exports: [
parentPageComponent
]
})
export class ParentModule{}

现在我们为子组件添加一些html、css和ts文件,例如按钮

// child.component.html
<div class="row center">
<div class="col-12">
<button class="button"> you are DOPE </button>
</div>
</div>
// child.component.scss
.button {
background: #ff0;
color: #000;
padding: 15px;
}
.center {
text-align: center;
}
// child.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
constructor() { }
ngOnInit() {}
}

接下来,我们通过修改html、css和ts文件来处理parent-page组件

// parent-page.component.html
<div class="parent">
<child></child>
</div>
// parent-page.component.scss
.parent {
margin: 0 auto;
max-width: 1200px;
background: #111;
}
// parent-page.compoent.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'parent-page',
templateUrl: './parent-page.html',
styleUrls: ['./parent-page.component.scss']
})
export class ParentPageComponent implements OnInit {
constructor() {}
ngOnInit() { }
}

您可以根据需要修改父内容和子内容。我希望这些代码片段可以帮助你解决你的问题!

一个解决方案是:只需键入ng g c mychildcomponent,然后粘贴此代码

<div class="row">
<div class="col-lg-12 align-evenly">
<button class="btn btn-primary btn-rounded right-margin">Monthly</button>
<button class="btn btn-primary btn-rounded right-margin">Quaterly</button>
</div>
</div>

现在在父组件中,在主html 中执行此操作

<app-mychild-component></app-mychild-component>

我看到这篇文章,想分享我的答案。

  1. ng新组件应用程序
  2. ng生成组件父级
  3. ng生成组件子级

在app.component.html 中

<app-parent>
<app-child></app-child>
</app-parent>

在parent.com.ponent.html中:

<div class="parent">
<p>parent works!</p>
<ng-content></ng-content>
</div>

在child.component.html中:

<div class="child">
<p>child works!</p>
</div>

我这里有一个的例子

最新更新