How to add multiple components on same page?

2020-07-18 08:10发布

问题:

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.

Would the following work?

app.component.html:

<div>APP Component1</div>
<div>App Component2</div>

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!';
}

回答1:

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.


The main component

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!';
}

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!';
}

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!';
}


回答2:

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

@Component here, is called decorator and it applies to single class following it. So creating another class will not make any effect.

It is advised to create a new component with a new class. Variables and functions of that class will be in the scope of that component.