Angular in t Review Question
Angular in t Review Question
⬆ Back to Top
AngularJS Angular
⬆ Back to Top
3. What is TypeScript?
TypeScript is a typed superset of JavaScript created by Microsoft
that adds optional types, classes, async/await, and many other
features, and compiles to plain JavaScript. Angular built entirely in
TypeScript and used as a primary language. You can install it
globally as
document.body.innerHTML = greeter(user);
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{title}}</h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
⬆ Back to Top
Component Directive
Only one component can be present per Many directives can be used per
DOM element DOM element
⬆ Back to Top
9. What is a template?
A template is a HTML view where you can display data by binding
controls to properties of an Angular component. You can store your
component's template in one of two places. You can define it inline
using the template property, or you can define the template in a
separate HTML file and link to it in the component metadata using
the @Component decorator's templateUrl property.
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
⬆ Back to Top
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: []
})
export class AppModule { }
⬆ Back to Top
⬆ Back to Top
<button (click)="logout()"></button>
⬆ Back to Top
⬆ Back to Top
Below are the list of few commands, which will come handy while
creating angular projects
⬆ Back to Top
ngOnInit(){
//called after the constructor and called after the first
ngOnChanges()
}
}
⬆ Back to Top
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
⬆ Back to Top
⬆ Back to Top
@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)
);
}
⬆ Back to Top
⬆ Back to Top
ng generate component hero -it
⬆ Back to Top
<p *ngIf="user.age > 18">You are not eligible for student pass!</p>
⬆ Back to Top
⬆ Back to Top
<h3>
{{title}}
<img src="{{url}}" style="height:30px">
</h3>
In the example above, Angular evaluates the title and url properties
and fills in the blanks, first displaying a bold application title and
then a URL.
⬆ Back to Top
i. new
ii. increment and decrement operators, ++ and --
iii. operator assignment, such as += and -=
iv. the bitwise operators | and &
v. the template expression operators
⬆ Back to Top
1. {{expression}} 2. Interpolation,
From the source-
[target]="expression" 3. bind- Property, Attribute,
to-view(One-way)
target="expression" Class, Style
Data direction Syntax Type
⬆ Back to Top
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18); // June 18, 1987
}
⬆ Back to Top
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday |
date:'dd/MM/yyyy'}}</p>` // 18/06/1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
⬆ Back to Top
30. How do you chain pipes?
You can chain pipes together in potentially useful combinations as
per the needs. Let's take a birthday property which uses date
pipe(along with parameter) and uppercase pipes as below
@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);
}
⬆ Back to Top
@Pipe({name: 'myCustomPipe'})
v. The @Pipe decorator allows you to define the pipe name that
you'll use within template expressions. It must be a valid
JavaScript identifier.
⬆ Back to Top
@Pipe({name: 'customFileSizePipe'})
export class FileSizePipe implements PipeTransform {
transform(size: number, extension: string = 'MB'): string {
return (size / (1024 * 1024)).toFixed(2) + extension;
}
}
Now you can use the above pipe in template expression as below,
template: `
<h2>Find the size of a file</h2>
<p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
`
⬆ Back to Top
⬆ Back to Top
```javascript
/* JavaScript imports */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
⬆ Back to Top
```
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
fetchUser() {
this.userService.getProfile()
.subscribe(
(data: User) => this.userProfile = { ...data }, // success path
error => this.error = error // error path
);
}
⬆ Back to Top
For example, you can import observables and operators for using
HttpClient as below,
⬆ Back to Top
// Execute with the observer object and Prints out each item
source.subscribe(myObserver);
// => Observer got a next value: 1
// => Observer got a next value: 2
// => Observer got a next value: 3
// => Observer got a next value: 4
// => Observer got a next value: 5
// => Observer got a complete notification
⬆ Back to Top
⬆ Back to Top
interface Observer<T> {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
myObservable.subscribe(myObserver);
⬆ Back to Top
Observable Promise
Subscribe method is used for error handling which makes Push errors to the
centralized and predictable error handling child promises
⬆ Back to Top
⬆ Back to Top
myObservable.subscribe({
next(num) { console.log('Next num: ' + num)},
error(err) { console.log('Received an errror: ' + err)}
});
⬆ Back to Top
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Browse
Angular Element Support
r
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
is no `greet` property on `container`.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
ng serve
⬆ Back to Top
⬆ Back to Top
<base href="/">
⬆ Back to Top
⬆ Back to Top
<router-outlet></router-outlet>
<!-- Routed components go here -->
⬆ Back to Top
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
⬆ Back to Top
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of
todos</a>
<a routerLink="/completed" routerLinkActive="active">Completed
todos</a>
</nav>
<router-outlet></router-outlet>
⬆ Back to Top
⬆ Back to Top
i. NavigationStart,
ii. RouteConfigLoadStart,
iii. RouteConfigLoadEnd,
iv. RoutesRecognized,
v. GuardsCheckStart,
vi. ChildActivationStart,
vii. ActivationStart,
viii. GuardsCheckEnd,
ix. ResolveStart,
x. ResolveEnd,
xi. ActivationEnd
xii. ChildActivationEnd
xiii. NavigationEnd,
xiv. NavigationCancel,
xv. NavigationError
xvi. Scroll
⬆ Back to Top
@Component({...})
class MyComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map(p => p.id));
const url: Observable<string> = route.url.pipe(map(segments =>
segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map(d => d.user));
}
}
⬆ Back to Top
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
i. Just-in-Time (JIT)
ii. Ahead-of-Time (AOT)
⬆ Back to Top
ng build
ng serve
⬆ Back to Top
⬆ Back to Top
prod) compiles with AOT by default.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Component({
providers: [{
provide: MyService, useFactory: () => getService()
}]
})
function getService(){
return new MyService();
}
@Component({
providers: [{
provide: MyService, useFactory: getService
}]
})
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Component({
selector: 'app-root'
})
⬆ Back to Top
@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
⬆ Back to Top
xv. Function calls are not supported: The compiler does not
currently support function expressions or lambda functions.
For example, you cannot set a provider's useFactory to an
anonymous function or arrow function as below.
xvi. providers: [
xvii. { provide: MyStrategy, useFactory: function() { ... } },
xviii. { provide: OtherStrategy, useFactory: () => { ... } }
]
⬆ Back to Top
]
⬆ Back to Top
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
⬆ Back to Top
{
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
⬆ Back to Top
@Component({
selector: 'my-component',
template: '{{user.contacts.email}}'
})
class MyComponent {
user?: User;
}
template:
'{{ $any(user).contacts.email }}'
The $any() cast function also works with this to allow access to
undeclared members of the component.
template:
'{{ $any(this).contacts.email }}'
⬆ Back to Top
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.name}} contacted through
{{contact!.email}} </span>'
})
class MyComponent {
user?: User;
contact?: Contact;
⬆ Back to Top
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
ng new codelyzer
ng lint
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
state('open', style({
height: '300px',
opacity: 0.5,
backgroundColor: 'blue'
})),
⬆ Back to Top
state('close', style({
height: '100px',
opacity: 0.8,
backgroundColor: 'green'
})),
⬆ Back to Top
105. What is the purpose of animate function?
Angular Animations are a powerful way to implement sophisticated
and compelling animations for your Angular single page web
application.
@Component({
selector: 'app-animate',
templateUrl: `<div [@changeState]="currentState" class="myblock mx-
auto"></div>`,
styleUrls: `.myblock {
background-color: green;
width: 300px;
height: 250px;
border-radius: 5px;
margin: 5rem;
}`,
animations: [
trigger('changeState', [
state('state1', style({
backgroundColor: 'green',
transform: 'scale(1)'
})),
state('state2', style({
backgroundColor: 'red',
transform: 'scale(1.5)'
})),
transition('*=>state1', animate('300ms')),
transition('*=>state2', animate('2000ms'))
])
]
})
export class AnimateComponent implements OnInit {
@Input() currentState;
constructor() { }
ngOnInit() {
}
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
}
⬆ Back to Top
⬆ Back to Top
AngularJS Angular
Dependency injection tokens are Tokens can have different types. They are
always strings often classes and sometimes can be strings.
There is exactly one injector even There is a tree hierarchy of injectors, with a
though it is a multi-module root injector and an additional injector for
applications each component.
⬆ Back to Top
⬆ Back to Top
112. What are the features included in ivy
preview?
You can expect below features with Ivy preview,
⬆ Back to Top
{
"projects": {
"my-project": {
"architect": {
"build": {
"options": {
...
"aot": true,
}
}
}
}
}
}
⬆ Back to Top
⬆ Back to Top
"plugins": [
{"name": "@angular/language-service"}
]
Note: The completion and diagnostic services works for .ts files
only. You need to use custom plugins for supporting HTML files.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Note: You may need to refactor your initial scaffolding web worker
code for sending messages to and from.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Input() myProperty;
@Output() myEvent = new EventEmitter();
⬆ Back to Top
declarations: [
YourComponent,
YourPipe,
YourDirective
],
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
subject.next(2);
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
ng add @angular/bazel
⬆ Back to Top
135. How do you run Bazel directly?
Sometimes you may want to bypass the Angular CLI builder and run
Bazel directly using Bazel CLI. You can install it globally using
@bazel/bazel npm package. i.e, Bazel CLI is available under
@bazel/bazel package. After you can apply the below common
commands,
⬆ Back to Top
then run it.
⬆ Back to Top
⬆ Back to Top
@ViewChild('uname') input;
ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
⬆ Back to Top
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
⬆ Back to Top
140. How do you pass headers for HTTP client?
You can directly pass object map for http client or create
HttpHeaders class to supply the headers.
(or)
let headers = new HttpHeaders().set('header1', headerValue1); //
create header object
headers = headers.append('header2', headerValue2); // add a new
header, creating a new object
headers = headers.append('header3', headerValue3); // add another
header
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
buildTarget.options.optimization = true;
addBuildTargetOption();
⬆ Back to Top
⬆ Back to Top
It supports the most recent two versions of all major browsers. The
latest version of Angular material is 8.1.1
⬆ Back to Top
147. How do you upgrade location service of
angularjs?
If you are using $location service in your old AngularJS application,
now you can use LocationUpgradeModule(unified location service)
which puts the responsibilities of $location service
to Location service in Angular. Let's add this module to AppModule as
below,
// Other imports ...
import { LocationUpgradeModule } from '@angular/common/upgrade';
@NgModule({
imports: [
// Other NgModule imports...
LocationUpgradeModule.config()
]
})
export class AppModule {}
⬆ Back to Top
⬆ Back to Top
Note: A chrome browser also opens and displays the test output in
the "Jasmine HTML Reporter".
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
i. Angular 1:
Angular 1 (AngularJS) is the first angular framework
released in the year 2010.
AngularJS is not built for mobile devices.
It is based on controllers with MVC architecture.
ii. Angular 2:
Angular 2 was released in the year 2016. Angular 2 is a
complete rewrite of Angular1 version.
The performance issues that Angular 1 version had has
been addressed in Angular 2 version.
Angular 2 is built from scratch for mobile devices unlike
Angular 1 version.
Angular 2 is components based.
iii. Angular 3:
The following are the different package versions in
Angular 2:
@angular/core v2.3.0
@angular/compiler v2.3.0
@angular/http v2.3.0
@angular/router v3.3.0
The router package is already versioned 3 so to avoid
confusion switched to Angular 4 version and skipped 3
version.
iv. Angular 4:
The compiler generated code file size in AOT mode is
very much reduced.
With Angular 4 the production bundles size is reduced
by hundreds of KB’s.
Animation features are removed from angular/core and
formed as a separate package.
Supports Typescript 2.1 and 2.2.
Angular Universal
New HttpClient
v. Angular 5:
Angular 5 makes angular faster. It improved the loading
time and execution time.
Shipped with new build optimizer.
Supports Typescript 2.5.
Service Worker
vi. Angular 6:
It is released in May 2018.
Includes Angular Command Line Interface (CLI),
Component Development KIT (CDK), Angular Material
Package, Angular Elements.
Service Worker bug fixes.
i18n
Experimental mode for Ivy.
RxJS 6.0
Tree Shaking
vii. Angular 7:
It is released in October 2018.
TypeScript 3.1
RxJS 6.3
New Angular CLI
CLI Prompts capability provide an ability to ask
questions to the user before they run. It is like
interactive dialog between the user and the CLI
With the improved CLI Prompts capability, it helps
developers to make the decision. New ng commands
ask users for routing and CSS styles types(SCSS) and ng
add @angular/material asks for themes and gestures or
animations.
viii. Angular 8:
It is released in May 2019.
TypeScript 3.4
ix. Angular 9:
It is released in February 2020.
TypeScript 3.7
Ivy enabled by default
x. Angular 10:
It is released in June 2020.
TypeScript 3.9
TSlib 2.0
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
ng v
ng version
ng -v
ng --version
⬆ Back to Top
Browser Version
Chrome latest
Firefox latest
IE Mobile 11
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
161. What are the best practices for security in
angular?
Below are the best practices of security in angular,
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
165. What is Sanitization? Is angular supports it?
Sanitization is the inspection of an untrusted value, turning it into
a value that's safe to insert into the DOM. Yes, Angular suppports
sanitization. It sanitizes untrusted values for HTML, styles, and URLs
but sanitizing resource URLs isn't possible because they contain
arbitrary code.
⬆ Back to Top
⬆ Back to Top
<p>Interpolated value:</p>
<div >{{htmlSnippet}}</div>
<p>Binding of innerHTML:</p>
<div [innerHTML]="htmlSnippet"></div>
⬆ Back to Top
ii. Mark the trusted value by calling some of the below methods
a. bypassSecurityTrustHtml
b. bypassSecurityTrustScript
c. bypassSecurityTrustStyle
d. bypassSecurityTrustUrl
e. bypassSecurityTrustResourceUrl
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>>
}
You can use interceptors by declaring a service class that
implements the intercept() method of the HttpInterceptor interface.
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
...
}
}
@NgModule({
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true
}
]
...
})
export class AppModule {}
⬆ Back to Top
i. Authentication
ii. Logging
iii. Caching
iv. Fake backend
v. URL transformation
vi. Modifying headers
⬆ Back to Top
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyFirstInterceptor, multi:
true },
{ provide: HTTP_INTERCEPTORS, useClass: MySecondInterceptor, multi:
true }
],
⬆ Back to Top
}
}
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi:
true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
⬆ Back to Top
⬆ Back to Top
registerLocaleData(localeDe, 'de');
⬆ Back to Top
ng xi18n
ix. Merge the completed translation file into the app: You
need to use Angular CLI build command to compile the app,
choosing a locale-specific configuration, or specifying the
following command options.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
and the translation unit generated for first text in for German
language as
<h2>Guten Morgen</h2>
<h2>Guten Morgen</h2>
⬆ Back to Top
⬆ Back to Top
184. How can I translate attribute?
You can translate attributes by attaching i18n-x attribute where x is
the name of the attribute to translate. For example, you can
translate image title attribute as below,
<img [src]="example" i18n-title title="Internationlization" />
By the way, you can also assign meaning, description and id with
the i18n-x="|@@" syntax.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
If you use the JIT compiler, specify the warning level in the compiler
config at bootstrap by adding the 'MissingTranslationStrategy'
property as below,
platformBrowserDynamic().bootstrapModule(AppModule, {
missingTranslation: MissingTranslationStrategy.Error,
providers: [
// ...
]
});
⬆ Back to Top
Note: You can create own third party library and publish it as npm
package to be used in an Application.
⬆ Back to Top
⬆ Back to Top
constructor(myElement: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
⬆ Back to Top
⬆ Back to Top
193. What is protractor?
Protractor is an end-to-end test framework for Angular and
AngularJS applications. It runs tests against your application running
in a real browser, interacting with it as a user would.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit(): void {
$(document).ready(() => {
$('#elementId').css({'text-color': 'blue', 'font-size':
'150%'});
});
}
}
⬆ Back to Top
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
⬆ Back to Top
⬆ Back to Top
But if you are changing your existing style in your project then
use ng set command,
ng set defaults.styleExt scss
⬆ Back to Top
⬆ Back to Top
For example, you can provide 'hello' list based on a greeting array,
@Component({
selector: 'list-pipe',
template: `<ul>
<li *ngFor="let i of greeting | slice:0:5">{{i}}</li>
</ul>`
})
export class PipeListComponent {
greeting: string[] = ['h', 'e', 'l', 'l', 'o', 'm','o', 'r', 'n',
'i', 'n', 'g'];
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
<div [ngSwitch]="currentBrowser.name">
<chrome-browser *ngSwitchCase="'chrome'"
[item]="currentBrowser"></chrome-browser>
<firefox-browser *ngSwitchCase="'firefox'"
[item]="currentBrowser"></firefox-browser>
<opera-browser *ngSwitchCase="'opera'"
[item]="currentBrowser"></opera-browser>
<safari-browser *ngSwitchCase="'safari'"
[item]="currentBrowser"></safari-browser>
<ie-browser *ngSwitchDefault [item]="currentItem"></ie-
browser>
</div>
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
210. Is mandatory to pass static flag for
ViewChild?
In Angular 8, the static flag is required for ViewChild. Whereas in
Angular9, you no longer need to pass this property. Once you
updated to Angular9 using ng update, the migration will remove
{ static: false } script everywhere.
@ViewChild(ChildDirective) child: ChildDirective; // Angular9 usage
@ViewChild(ChildDirective, { static: false }) child:
ChildDirective; //Angular8 usage
⬆ Back to Top
i. Pipe operator
ii. Safe navigation operator
iii. Non-null assertion operator
⬆ Back to Top
⬆ Back to Top
Basically, there are two main kinds of entry components which are
following -
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
220. Is it all components generated in production
build?
No, only the entry components and template components appears
in production builds. If a component isn't an entry component and
isn't found in a template, the tree shaker will throw it away. Due to
this reason, make sure to add only true entry components to reduce
the bundle size.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@NgModule({
imports: [
CommonModule
],
declarations: []
})
export class MyCustomFeature { }
⬆ Back to Top
⬆ Back to Top
Extend the entire application with services by Can't extend the application
adding providers to provides array with services
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Injectable({
providedIn: 'root', //Angular provide the service in root injector
})
export class MyService {
}
⬆ Back to Top
233. What is the recommendation for provider
scope?
You should always provide your service in the root injector unless
there is a case where you want the service to be available only if
you import a particular @NgModule.
⬆ Back to Top
⬆ Back to Top
ix. @NgModule({
x. ...
xi. providers: [MyService],
xii. ...
})
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@NgModule({
imports: [ CommonModule ],
declarations: [ UserComponent, NewUserDirective, OrdersPipe ],
exports: [ UserComponent, NewUserDirective, OrdersPipe,
CommonModule, FormsModule ]
})
export class SharedModule { }
⬆ Back to Top
⬆ Back to Top
...
constructor(@Inject(LOCALE_ID) locale) {
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
xv. HTTP Data Request: You can get data from a server through
an HTTP request
xvi. data = 'default value';
xvii. constructor(private httpClient: HttpClient) {}
xviii.
xix. ngOnInit() {
xx. this.httpClient.get(this.serverUrl).subscribe(response => {
xxi. this.data = response.data; // change detection will
happen automatically
xxii. });
}
xxx. Micro tasks Promises: You can update the data in the
callback function of promise
xxxi. data = 'initial value';
xxxii.
xxxiii. ngOnInit() {
xxxiv. Promise.resolve(1).then(v => {
xxxv. this.data = v; // Change detection will happen
automatically
xxxvi. });
}
xxxvii. Async operations like Web sockets and Canvas: The data
can be updated asynchronously using
WebSocket.onmessage() and Canvas.toBlob().
⬆ Back to Top
zone.run(() => {
// outside zone
expect(zoneThis).toBe(zone);
setTimeout(function() {
// the same outside zone exist here
expect(zoneThis).toBe(zone);
});
});
⬆ Back to Top
ix. onHasTask: This hook triggers when the status of one kind of
task inside a zone changes from stable(no tasks in the zone)
to unstable(a new task is scheduled in the zone) or from
unstable to stable.
x. onHasTask: function(delegate, curr, target, hasTaskState) {
xi. console.log('task state changed in the zone:',
hasTaskState);
xii. return delegate.hasTask(target, hasTaskState);
}
⬆ Back to Top
⬆ Back to Top
/
*********************************************************************
******************************
* Zone JS is required by default for Angular.
*/
import `./zone-flags`;
import 'zone.js/dist/zone'; // Included with Angular CLI.
⬆ Back to Top
toggle() {
this.isUp = !this.isUp;
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
@Component({
selector: 'user-profile',
styleUrls: ['./user-profile.component.css']
template: `
<label>
User name:
<input type="text" [formControl]="userName">
</label>
`
})
export class UserProfileComponent {
userName = new FormControl('');
}
```
⬆ Back to Top
257. What are dynamic forms?
Dynamic forms is a pattern in which we build a form dynamically
xvii. Bind the form from template to the component using ngModel
syntax
xviii. <input type="text" class="form-control" id="name"
xix. required
[(ngModel)]="model.name" name="name">
<form #registerForm="ngForm">
```html
<div class="container">
<h1>Registration Form</h1>
<form (ngSubmit)="onSubmit()" #registerForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Please enter your name
</div>
</div>
<button type="submit" class="btn btn-success"
[disabled]="!registerForm.form.valid">Submit</button>
</form>
</div>
```
⬆ Back to Top
Form custom
Defined as Functions Defined as Directives
validation
⬆ Back to Top
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div formGroupName="address">
<h3>Address</h3>
<label>
Street:
<input type="text" formControlName="street">
</label>
<label>
City:
<input type="text" formControlName="city">
</label>
<label>
State:
<input type="text" formControlName="state">
</label>
<label>
Zip Code:
<input type="text" formControlName="zip">
</label>
</div>
<button type="submit" [disabled]="!
userProfile.valid">Submit</button>
</form>
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div>
<p>Add items</p>
<ul formArrayName="items">
<li *ngFor="let item of orderForm.controls.items.controls;
let i = index">
<input type="text" formControlName="{{i}}">
<button type="button" title="Remove Item"
(click)="onRemoveItem(i)">Remove</button>
</li>
</ul>
<button type="button" (click)="onAddItem">
Add an item
</button>
</div>
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Form control
If true If false
state
⬆ Back to Top
Now, your form model resets the form back to its original pristine
state.
⬆ Back to Top
this.myForm = formBuilder.group({
firstName: ['value'],
lastName: ['value', *Some Sync validation function*],
email: ['value', *Some validation function*, *Some asynchronous
validation function*]
});
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
<ng-container *ngIf="items">
<ul *ngFor="let item of items">
<li></li>
</ul>
</ng-container>
⬆ Back to Top
⬆ Back to Top
console.log(this.router.url); // /routename