Metadata is used to decorate the class so that it can configure the expected behavior of a class. Decorators are the core concept when developing with Angular (versions 2 and above). The user can use metadata to a class to tell Angular app that AppComponent is the component. Metadata can be attached to the TypeScript using the decorator.
@Component({ selector: 'app-root', templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] })
@Component is a decorator which makes use of configuration object to
create the component and its view.
Syntax: {{ expression }}
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({ // The Injectable decorator is required for dependency injection to work
// providedIn option registers the service with a specific NgModule
providedIn: 'root', // This declares the service with the root app (AppModule)
})
export class RepoService{
constructor(private http: Http){
}
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}
<li *ngFor="let user of users">
{{ user }}
</li>
<h3>
{{title}}
<img src="{{url}}" style="height:50px">
</h3>
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'fullDate' | uppercase}} </p>` // THURSDAY, JUNE 18, 1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
getUserResponse(): Observable<HttpResponse<User>> {
return this.http.get<User>(
this.userUrl, { observe: 'response' });
}
Interface OnInit {
ngOnInit() : void
}
fetchUser() {
this.userService.getProfile()
.subscribe(
(data: User) => this.userProfile = { ...data }, // success path
error => this.error = error // error path
);
}
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
{ path: ‘example’, loadChildren: ‘./example/example.module#ExampleModule’, component: PublicComponent },
<p *ngIf="display">Show this only if the Boolean "display" is true</p>
<tr *ngFor="let student of students; let i = index"> <td>{{student.name}}
</td> <td>{{i}}</td> </tr>​
$apply()
function. (@Pipe({name: 'myCustomPipe'}))
<p>Size: {{number | myCustomPipe: 'Error'}}</p>
<h2> {{apptitle}} <img src="{{imgname}}" style="height:30px"> </h2>
[(ngModel)] = “propertyvalue”
. ng build ng serve
ng build --aot ng server –aot
npm
CLI client. ng update @angular/cli@8 @angular/core@8
ng update @angular/cli @angular/core
Reasons | Details |
---|---|
Faster rendering | With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the application first. |
Fewer asynchronous requests | The compiler inlines external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files. |
Smaller Angular framework download size | There's no need to download the Angular compiler if the application is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload. |
Detect template errors earlier | The AOT compiler detects and reports template binding errors during the build step before users can see them. |
Better security | AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks. |
Angular compile | Details |
---|---|
Just-in-Time (JIT) | Compiles your application in the browser at runtime. This was the default until Angular 8. |
Ahead-of-Time (AOT) | Compiles your application and libraries at build time. This is the default starting in Angular 9. |
ng build
(build only) or ng serve
(build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the aot
property in your build configuration specified in angular.json
. By default, aot
is set to true
for new CLI applications. @Component()
and @Input()
, or implicitly in the constructor declarations of the decorated classes. The metadata tells Angular how to construct instances of your application classes and interact with them at runtime.@Component()
metadata object and the class constructor tell Angular how to create and display an instance of TypicalComponent
.@Component({
selector: 'app-typical',
template: '<div>A typical component for {{data.name}}</div>'
})
export class TypicalComponent {
@Input() data: TypicalData;
constructor(private someService: SomeService) { … }
}
TypicalComponent
. When it needs to create a TypicalComponent
instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.Phase | Details | |
---|---|---|
1 | code analysis | In this phase, the TypeScript compiler and AOT collector create a representation of the source. The collector does not attempt to interpret the metadata it collects. It represents the metadata as best it can and records errors when it detects a metadata syntax violation. |
2 | code generation | In this phase, the compiler's StaticReflector interprets the metadata collected in phase 1, performs additional validation of the metadata, and throws an error if it detects a metadata restriction violation. |
3 | template type checking | In this optional phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates. You can enable this phase explicitly by setting the fullTemplateTypeCheck configuration option; see Angular compiler options. |
JIT | AOT |
---|---|
JIT downloads the compiler and compiles code exactly before Displaying in the browser. | AOT has already complied with the code while building your application, so it doesn’t have to compile at runtime. |
Loading in JIT is slower than the AOT because it needs to compile your application at runtime. | Loading in AOT is much quicker than the JIT because it already has compiled your code at build time. |
JIT is more suitable for development mode. | AOT is much suitable in the case of Production mode. |
Bundle size is higher compare to AOT. | Bundle size optimized in AOT, in results AOT bundle size is half the size of JIT bundles. |
You can run your app in JIT with this command: ng build OR ng serve |
To run your app in AOT you have to provide –aot at the end like: ng build --aot OR ng serve --aot |
You can catch template binding error at display time. | You can catch the template error at building your application. |
Angular v11 | Angular v12 | Angular v13 |
TypeScript 4.0 | TypeScript 4.2 | TypeScript 4.4 |
Webpack 5 Support | Webpack 5.37 Support | Webpack 5.37 Support |
Migration to ESLint | Migrating from legacy i18n message IDs | View Engine is no longer available |
Deprecation of IE 9, 10, and IE mobile | Deprecating support for IE 11 | End of IE 11 support |
Updates on Operation Byelog | Improved component tests harness | Improvements to the Angular CLI |
Updated Language Service Preview | Updated Language Service Preview | Improvements to Angular tests |
Strict checks with a flag | Default strict mode | Framework changes and dependency updates |
Roadmap to provide early feedback | Roadmap to inform about the priorities of the Angular team | Support to Adobe Fonts |
Linting | Migration to default IVY-based language service | Changes to the Angular Package Format (APF) |
Improved Ngcc compiler | Improved logging and reporting | PR merges from community |
Updated Hot Module Replacement (HMR) Support | HTTP improvements | Component API updates |
npm install --global @angular/cli@next
ng version
@angular/core@14 @angular/cli@14
which should bring you to version 14 of Angular.aotSummaries
from TestBed
since Angular no longer needs them in Ivy.requests. JSONP
does not supports headers and if specified the HTTP module will now throw an error rather than ignoring them.initialNavigation: 'enabled'
to initialNavigation: 'enabledBlocking'
.pathMatch
, you may have to cast it to Route
or Routes
explicitly. Route.pathMatch
is no longer compatible with string
type.LoadChildrenCallback
now has a stricter type parameter Type<any>|NgModuleFactory<any>
rather than any
.setTimeout
. Make sure your tests do not rely on this behavior.LocationStrategy
interface now requires definition of getState()
.+
as part of a query no longer requires workarounds since +
no longer sends a space.AnimationDriver
now requires the getParentElement
method.resolver
from RouterOutletContract.activateWith
function and the resolver
from OutletContext
class since factory resolvers
are no longer needed.Router.initialUrl
accepts only UrlTree
to prevent a misuse of the API by assigning a string
value.@Component
decorator and specifying an array of CSS files or a string of CSS code. These styles will only be applied to the component they are associated with.style
" or "styleUrls" properties in the template tag.ngStyle
and ngClass
directives to bind styles and classes to a component based on conditionals.import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div [ngStyle]="{'color': myColor}">Hello World!</div>
`,
styles: [`
div {
font-size: 20px;
}
`]
})
export class AppComponent {
myColor = 'blue';
}
ngStyle
..spec.ts
" extension. For example, if you have a component named "MyComponent", create a new file named "my.component.spec.ts
".HttpClient
service, you would import the HttpClientModule
.describe()
function to create the test suite. The first argument is a string that describes what is being tested, and the second argument is a function that contains the tests.it()
function to write individual tests. The first argument is a string that describes the test, and the second argument is a function that contains the test code.TestBed.createComponent()
function creates a new instance of a component for testing.expect().toEqual()
matcher checks that the actual value is equal to the expected value.MyComponent
":
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should create the component', () => {
expect(component).toBeTruthy();
});
});
In this example, we import the necessary testing dependencies, create a new test suite using the describe()
function, create a new instance of the component using the TestBed.createComponent()
function, and write a simple test using the expect().toBeTruthy()
matcher to check that the component was created successfully.