A sample program to create a new component and bind to existing component.
Step 1: Create a new component
Create a new component in a new file app.newComponent.ts
import { Component } from '@angular/core';
@Component({
selector: 'new-comp',
template: `
<div>New Component</div>
`,
styles: [
`div{
border :1px solid black;
}`
]
})
export class NewComponent {
}
A component must have a class with a decorator @Component
The
@Component
must have the selector & template attribute.
Here the component name is
NewComponent
and this will be rendered wherever the selector is implemented
Step 2: Bind the new app component in the NgModule declaration
In order to use the new component, we must add it in the NgModule declaration class
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NewComponent } from './app.newcomponent'; //file path imported
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ,NewComponent
], //NewComponent class refrence added it
bootstrap: [ AppComponent ]
})
export class AppModule { }
Things to Know:
The
import { NewComponent } from './app.newcomponent';
statement added for new file name
NewComponent
class is added in the declarations section
Step 3: Bind the new component to the appcomponent
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
Main Content<br><br>
<new-comp></new-comp>
`
})
export class AppComponent {
}
Things to know:
<new-comp></new-comp>
- Here the angular js will render the newComponent content html
Program Execution
Live Example code
Program Output:
Main Content
New Component
Awaiting for Administrator approval