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!';
}
Every component must be declared in one—and only one—Angular module. Open app.
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.
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!';
}
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!';
}
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!';
}
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With