1. Create angular component (Standalone and without standalone)
- To create a angular component (standalone) use
ng g c component-name --standalone true --skip-tests
- To create a angular component (without standalone.) use
ng g c component-name --standalone false --skip-tests
Note
When
standalone
is set tofalse
, it updates theapp.module.ts
file, and our new component is registered there.
2. Use child class and child class method into parent class:
There are 3 ways of calling our component app.component.html
- By using custom tag
- By using class selector
- By using attribute
Custom Tag (by default)
In app.component.html
, if we call the child component using its tag, we can see the result:
<h1>Hello Shoyeb</h1>
<app-user></app-user> // Call like this
<app-user></app-user>
<br>
{{title}}
<br>
{{name}}
<br>
{{HelloMessage()}}
Here is app.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'NgLab';
name = 'Mohammad Adil';
HelloMessage(){
return "Hello Shoyeb from function";
}
}
Here is user.component.ts
:
import { Component } from '@angular/core';
@Component({ // This (Component) is metadata
selector: 'app-user', // Keep default
templateUrl: './user.component.html',
styleUrl: './user.component.css'
})
export class UserComponent {
}
Class Selector:
In app.component.html
, if we call the child component using its class, we can see the result:
<h1>Hello Shoyeb</h1>
<div class="app-user"> // Call like this
</div>
Here is user.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: '.app-user', // Use dot (.) in selector
templateUrl: './user.component.html',
styleUrl: './user.component.css'
})
export class UserComponent {
}
Use Attribute:
In app.component.html
, if we call the child component using its class, we can see the result:
<h1>Hello Shoyeb</h1>
<div app-user> // Call like this
</div>
Here is user.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: '[app-user]', // Use third bracket in selector
templateUrl: './user.component.html',
styleUrl: './user.component.css'
})
export class UserComponent {
}