如何在同一页面上添加多个组件? [英] How to add multiple components on same page?
问题描述
我刚刚启动了Angular应用,所以我想在同一页面上添加多个组件.在Angular中如何工作?假设每个div和视图都是一个单独的组件.这些组件必须位于单独的.ts文件中.
I just started an Angular app so I want to add multiple components on same page. How does this work in Angular? Let's assume each div will be a separate component as well as the view. The components must be in separate .ts files.
以下工作吗?
app.component.html:
app.component.html:
<div>APP Component1</div>
<div>App Component2</div>
app.component.ts:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent1 {
title = 'app works!';
}
export class AppComponent2 {
title = 'app works!';
}
推荐答案
为此,您实际上需要3个组件. Angular应用程序的主要组件,以及要显示的两个组件.这将给出以下文件结构.
In order to do that, you actually need 3 components. The main component of the Angular application, and the two components you want to display. That would give the following file structure.
app.component.html :
<div>{{title}}</div>
<app-comp1></app-comp1>
<app-comp2></app-comp2>
app.component.ts :
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'App works!';
}
n°1分量
comp1.component.html :
Component n°1
comp1.component.html:
<div>{{title}}</div>
comp1.component.ts :
import { Component } from '@angular/core';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class AppComponent1 {
title = 'AppComponent1 works!';
}
分量n°2
comp2.component.html :
Component n°2
comp2.component.html:
<div>{{title}}</div>
comp2.component.ts :
import { Component } from '@angular/core';
@Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.css']
})
export class AppComponent2 {
title = 'AppComponent2 works!';
}
这篇关于如何在同一页面上添加多个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!