javascript component based framework, for building SPA
building blocks for Angular. It consists of
// app.component.ts
@Component({
selector: 'app-root', /* defines how the component is identified and utilized in html templates */
template: '<div></div>', /* innline HTML template for the component */
templateUrl: './app.component.html', /* Path to an external HTML template file */
styleUrls: ['./app.component.css'], /* Array of paths to external CSS files */
styles: ['h1 { color: blue; }'], /* Inline styles */
providers: [ExampleService], /* Array of service providers for dependency injection. */
viewProviders: [ExampleViewService], /* Array of view service providers*/
changeDetection: ChangeDetectionStrategy.OnPush, /* Specifies change detection strategy for component. */
encapsulation: ViewEncapsulation.Emulated, /* Defines encapsulation strategy for component's styles. */
moduleId: module.id /* A string representing the moduleId to use for template and style files. */
animations: [trigger('myAnimation', [/* animation metadata */])]
})
export class AppComponent {
title = 'My Angular App';
}
used to manipulate the structure of the DOM. need to use * before this.
<span *ngIf="booleanValue"></span>
<span *ngFor="let i of names; let n =index"></span>
<div [ngSwitch]="Switch_Expression">
<div *ngSwitchCase="MatchExpression1”> First Template</div>
<div *ngSwitchCase="MatchExpression2">Second template</div>
<div *ngSwitchDefault?>Default Template</div>
</div>
Note: ngIf & ngFor on same div, will result in an an Template parse errors
[ngStyle]="{backgrounColor: getColor()}
<span [ngClass]="{className: status=='1'}">RAJESH</span>
selector in component
@Directive({ selector: '[appHighlight]'})
export class HighlightDirective {
constructor(private eleRef: ElementRef) { eleRef.nativeElement.style.background = 'red'; }
}
binding data into html template
[property]="expression"
HTML element properties such as src, disabled, value, innerHtml, title
[attr.property]="expression"
attr.placeholder,attr.colspan,attr.aria-label[class.className]="expression"
[style.styleProperty]="expression"
(event)="function($event)"
events are click, input, keyup, mouseover, mouseout, change, focus, blur
[(ngModel)] <input type="text" [(ngModel)]="val" (ngModelChange)="change($event)">
reusable common functionality/data across multiple components
//sample.service.ts
@injectable
export class SampleService{
public getSomething() { return "Hello world"; }
}
group of components, directives, pipes, services based on functionality
// app.module.ts
@NgModule({
declarations: [AppComponent], /* array of components,directives,pipes created */
imports: [BrowserModule], /* array of modules */
exports: [BrowserModule], /* array of modules to export */
providers: [], /* array of services */
bootstrap: [AppComponent], /* only given for root component */
entryComponent: [] /* will put dynamic components */
})
export class AppModule { }
//child.component.ts
@Input('customname') name:string
@Output sendData:EventEmitter<any> = new EventEmitter<any>();
onSubmit(){ this.sendData.emit("from child to parent");}
//parent.component.html
<app-child custom name='rajesh' (sendData)="someFunctionInParent($event)"></app-child>
//parent.component.ts
export ParentComponent{someFunctionInParent(event){console.log(event);}}
used to Transform the Data.
syntax is value | pipeName surrounded by double flower bracket
i) uppercase, lowercase
ii) 6589.23 | currency:’USD’
iii) todayDate | date:’d/M/y’
iv) todayDate | date:’shortTime’
v) json
vi) ‘Angular Pipes’ | slice:8:13
@Pipe({ name: 'sqrt', pure: true }) // pure is true by default
export class SqrtPipe implements PipeTransform {
transform(val : number) : number {
return Math.sqrt(val);
}
}
Host: element is the element on which we attach our directive or component HostBinding:binds element property to host
@Directive({selector: '[appHighLight]',})
export class HighLightDirective implements OnInit {
@HostBinding('attr.title') title = 'This is a custom directive';
@HostBinding('id') id = 'customDirectiveId'; //HTML attributes such as title, id, class, style
@HostBinding('style.border') border: string="5px solid blue";
@HostBinding('disabled') disabled = true; //Element Properties: such as disabled, hidden, readonly, etc.
@HostBinding('class.active') isActive = true; //control classes of the host elemen
}
HostListener: listens to the DOM event of host.
@HostListener('click', ['$event'])
onClick(event: MouseEvent) { console.log('Element clicked', event);}
@HostListener('mouseenter')
onMouseEnter() { console.log('Mouse entered'); }
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) { console.log('Key pressed', event.key); }
@HostListener('window:resize', ['$event'])
onResize(event: Event) { console.log('Window resized', event); }
@HostListener('customEvent', ['$event'])
onCustomEvent(event: CustomEvent) { console.log('Custom event triggered', event.detail); }
it contains html template. reuse by ngTemplateOutlet and template reference variable
<ng-template #sampleTemplate>From inside template will print, wherever #sampletemplate called</ng-template>
//using below ng-container we can reuse ng-template html
<ng-container *ngTemplateOutlet="sampleTemplate">
This text is not displayed
</ng-container>
<!--one way binding-->
<input type="text" #inputTemplate /> <button (click)="submitted(inputTemplate.value)">submit</button>
<!--two way binding-->
<input type="text" #inputTemplate ngModel /> <button (click)="submitted(inputTemplate.value)">submit</button>
<div *ngIf="selected; then thenBlock1 else elseBlock1"><p>This content is not shown</p></div>
<ng-template #thenBlock1> <p>content to render when the selected is true.</p> </ng-template>
<ng-template #elseBlock1> <p>content to render when selected is false.</p></ng-template>
Command | Description |
---|---|
Install Nodejs and npm | Nodejs |
npm install –g @angular/cli |
install Angular cli |
ng –version |
check version |
ng new projectname |
create new angular project |
ng serve |
run project |
ng g c componentname |
generate new component |
ng g m modulename |
generate new module |
ng g p pipename |
generate new pipe |
ng g directive directivename |
generate new directive |
ng g s servicename |
generate new service |
ng build |
build and generate dist |
<app-root></app-root>
e2e -> has e2e test files
node_modules -> contains all the libraries and dependencies mentioned in the package.json file.
src
app -> contains the components, modules, services, etc.,
assets -> contains static assets like images, fonts, etc.
environments -> contains environment-specific configuration files
favicon.ico -> icon file that appears in the browser tab.
index.html -> main HTML file that serves as the entry point
main.ts -> main ts file that bootstraps Angular app.
style.css -> Global style sheet apply entire app
tslint.json -> extension of root folder file(tslint.json)
tsconfig.app.json -> extension of root folder file(tsconfig.json)
test.ts -> will have all test cases register here
polyfills.ts -> it required to support various browsers
angular.json -> has assets, root, script, env details , main.ts path
package.json -> has dependencies, dev dependencies, scrip command details
package.lock.json -> has dependencies needed for dependencies mentioned in package json
tsconfig.json -> specifies compiler options and file inclusion/exclusion rules.
tslint.json -> config file for linting ts. used to enforce coding standards and catch errors.
describe
, it
, expect
).import { TestBed } from '@angular/core/testing';
import { MyComponent } from './my-component';
describe('MyComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
}).compileComponents();
});
it('should create the component', () => {
const fixture = TestBed.createComponent(MyComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
describe('Angular App', () => {
it('should load the home page', () => {
cy.visit('/');
cy.contains('Welcome to Angular');
});
it('should navigate to about page', () => {
cy.get('a[routerLink="/about"]').click();
cy.url().should('include', '/about');
});
});
angular.json, tsconfig.json, package.json, polyfills.ts
ng build
a
npm install --save bootstrap
ii) angular-cli.json, add "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css","styles.css"]