Angular 嵌套组件如何在角度5或角度6中工作

Angular 嵌套组件如何在角度5或角度6中工作,angular,angular5,angular6,Angular,Angular5,Angular6,我试图学习两个或多个组件如何在角度上相互通信。因此,在创建了一个角度项目之后,我刚刚创建了四个新组件,分别命名为1、2、3和4 之后,我尝试在app.component.html中添加此代码 <app-one> <app-two> <app-three> </app-three> </app-two> <app-four> </app-four> </app-on

我试图学习两个或多个组件如何在角度上相互通信。因此,在创建了一个角度项目之后,我刚刚创建了四个新组件,分别命名为1、2、3和4

之后,我尝试在app.component.html中添加此代码

<app-one> 
    <app-two>
        <app-three> </app-three>
    </app-two>
     <app-four> </app-four>
</app-one>
通过这样做,我认为其中一个将成为所有组件的父组件,并且所有组件都将渲染。但不幸的是,我只有

one works!

而其他组件根本不渲染。我确信我在角度和它的工作方式方面有一些严重的问题。你能解释一下为什么它不呈现二,三,四的数据吗?如果我想让它们工作,我应该怎么做?

理想情况下,每个组件模板都负责自己的html。依我看,这是最好的处理方法

根组件的模板

@组件({
选择器:“”,
模板:“”
})
导出类RootComponent{}
组件1的模板

@组件({
选择器:“应用程序一”,
模板:“”
})
导出类child1组件{}
组件2的模板

@组件({
选择器:“应用程序二”,
模板:“”
})
导出类child2组件{}
组件3的模板

@组件({
选择器:“应用程序三”,
模板:“你好,从3开始”
})
导出类child3组件{}
组件4的模板

@组件({
选择器:“应用程序四”,
模板:“你好,从4开始”
})
导出类child4组件{}

理想情况下,每个组件模板都负责自己的html。依我看,这是最好的处理方法

根组件的模板

@组件({
选择器:“”,
模板:“”
})
导出类RootComponent{}
组件1的模板

@组件({
选择器:“应用程序一”,
模板:“”
})
导出类child1组件{}
组件2的模板

@组件({
选择器:“应用程序二”,
模板:“”
})
导出类child2组件{}
组件3的模板

@组件({
选择器:“应用程序三”,
模板:“你好,从3开始”
})
导出类child3组件{}
组件4的模板

@组件({
选择器:“应用程序四”,
模板:“你好,从4开始”
})
导出类child4组件{}

如果需要嵌套组件,请在父组件中使用
ng content
,例如

@Component({
  selector: 'root',
  template: '<div>I'm root, <ng-content></ng-content></div>'
})
export class RootComponent{}


@Component({
  selector: 'child',
  template: '<root>I'm children in the root</root>'
})
export class ChildComponent{}
它将呈现
我是root,你好,世界


如果需要嵌套组件,请在父组件中使用
ng content
,例如

@Component({
  selector: 'root',
  template: '<div>I'm root, <ng-content></ng-content></div>'
})
export class RootComponent{}


@Component({
  selector: 'child',
  template: '<root>I'm children in the root</root>'
})
export class ChildComponent{}
它将呈现
我是root,你好,世界


您的组件类中有哪些代码?@codeVerses我已更新了类信息。请看一看。我刚刚用ng g c one等创建了所有组件。没什么特别的。刚刚诞生了一个组件。您的组件类中有什么代码?@codeVerses我已经更新了类信息。请看一看。我刚刚用ng g c one等创建了所有组件。没什么特别的。刚刚有新的组件,非常感谢。但是你能告诉我为什么上面的方法不起作用吗?是因为一个类的组件不知道其他的组件吗?@Kazi-请看我刚才添加的链接。@Kazi由于转换,它不起作用。请看我下面关于ng-content的回答。非常感谢。但是你能告诉我为什么上面的方法不起作用吗?是因为一个类的组件不知道其他的组件吗?@Kazi-请看我刚才添加的链接。@Kazi由于转换,它不起作用。请参阅我下面关于ng内容的回答。
@Component({
  selector: 'app-one',
  template: '<app-two></app-two><app-four></app-four>'
})
export class Child1Component{}
@Component({
  selector: 'app-two',
  template: '<app-three></app-three>'
})
export class Child2Component{}
@Component({
  selector: 'app-three',
  template: '<h1>Hi there from 3</h1>'
})
export class Child3Component{}
@Component({
  selector: 'app-four',
  template: '<h1>Hi there from 4</h1>'
})
export class Child4Component{}
@Component({
  selector: 'root',
  template: '<div>I'm root, <ng-content></ng-content></div>'
})
export class RootComponent{}


@Component({
  selector: 'child',
  template: '<root>I'm children in the root</root>'
})
export class ChildComponent{}
<child></child>
<root>Hello world!</root>