Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple components on same page?

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!';
}
like image 781
hussain Avatar asked Nov 21 '17 15:11

hussain


People also ask

Can you have multiple components in angular?

Every component must be declared in one—and only one—Angular module. Open app.

What is nested components in angular?

What is a Nested Component? Angular allows us to have a different child, or nested component, which is the same component we normally use in an Angular application. The difference between them is that this child component contains the logic which can be used into the parent component as a single unit.


2 Answers

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!';
}
like image 163
Adrien Brunelat Avatar answered Oct 22 '22 10:10

Adrien Brunelat


@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.

like image 43
Ronit Mukherjee Avatar answered Oct 22 '22 10:10

Ronit Mukherjee