Skip to content

Instantly share code, notes, and snippets.

@spabloramirez
Last active April 3, 2018 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spabloramirez/6dbba2d98acb9921b055e783b7ea350c to your computer and use it in GitHub Desktop.
Save spabloramirez/6dbba2d98acb9921b055e783b7ea350c to your computer and use it in GitHub Desktop.

Install Angular CLI

npm install -g angular-cli
ng help
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve --host 192.168.1.75 --port 3000

Generating Components, Directives, Pipes and Services

ng generate component my-new-component
ng generate component my-new-component/item
 [ --flat(no create subfolder) | --it (inline template) | --is (inline style) ]


String Interpolation {{data}}

<p>{{ serverId }}</p>
<p>{{ getServerId() }}</p>

Property Binding [property]="data"

<button [disable]="isEditMode"></button>

Event Binding (event)="data"

<button (click)="onSelect()"></button>
onSelect(){
	...
}

Pass event data

<input (input)="onInputText($event)"></input>
onInputText(event:Event){
	...
}

Set a value on controller

<button (click)="userName='Pablo'"></button>
<button (onChangeName)="userName=$event"></button> //set data from with an event emitted from a child component

Two-Way-Binding [(ngModel)]="data"

serverName = "myServer"; //prepopulate input value from controller

<input [(ngModel)]="serverName"></input>
<p>{{serverName}}

Explicit casting

(<HTMLInputElement>event.target).value

Directives

ngIf

<p *ngIf="isEditMode"></p> //It's not just hidden, it doesn't exist on the DOM

ngIf;else (angular4)

<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>

ngStyle

<p [ngStyle]="{'background-color:getColor()}"></p>//binding to a property of the directive
getColor(){
	return this.completed === true ? 'green':'red';
}

ngClass

<p [ngClass]="{class:variable === 'value'}"></p>

ngFor

<ul>
	<li *ngFor="let element of array; let i = index">
    {{element}}{{i}}
    </li>
</ul>

<presupuesto-item *ngFor="let presupuesto of presupuestoList" [presupuesto]="presupuesto">

ngContent

//parent componet
<child-component> 
	content from parent //this content will be pass to ng-content directive in the child component
</child-component>

//child component
<div>
	<ng-content></ng-content>
</div>

Bind custom property @Input

//parent component
<child-component [selectedTodo]=value>

//child component
@Input('selectedTodo')
todo

Bind custom event @Output

//parent component
<child-component (todoCreated)=onTodoAdded($event)>
onTodoAdded(todo:Todo){
	todoList.push(todo)
}

//child component
@Output('todoCreated')
todoCreated = new EventEmitter<Todo>();
onSubmit(){
	todoCreated.emit(todo);
}

Local Reference

<input #todoText></input>
<button (click)="onAddTodo=(todoText)"></button>
onAddTodo(input:HTMLInputElement){
	input.value
}

Local Reference from controller @ViewChild

<input #todoText></input>

@ViewChild('todoText')
todoText: ElementRef

onAddTodo(){
	this.todoText.nativeElement.value
}

Services

//module or component
providers: [LoggingService],

//loggin.service
export class LoggingService {
  logStatusChange(status: string) {
    console.log('A server status changed, new status: ' + status);
  }
}

//controller
constructor(private loggingService: LoggingService) {}
this.loggingService.logStatusChange(status)

Link store service to controller

export class AppComponent implements OnInit {
  accounts = [];

  constructor(private accountsService: AccountsService) {}
  ngOnInit() {
    this.accounts = this.accountsService.accounts;
  }
}

Inject a service into another service

Note:we need to provide it on app.module, and implemente @injectable decorator

@Injectable()
export class AccountsService {
	constructor(private loggingService: LoggingService) {}
  addAccount(name: string, status: string) {
    this.accounts.push({name: name, status: status});
    this.loggingService.logStatusChange(status);
  }
}

Using service for push notifications Nota: retornar array.slice() para cree una copia y no pueda se modificado

export class ShoppingListService {
  ingredientsChanged = new EventEmitter<Ingredient[]>();
  private ingredients: Ingredient[] = [];

  getIngredients() {
    return this.ingredients.slice();
  }

  addIngredient(ingredient: Ingredient) {
    this.ingredients.push(ingredient);
    this.ingredientsChanged.emit(this.ingredients.slice());
  }

  addIngredients(ingredients: Ingredient[]) {    
    this.ingredients.push(...ingredients);
    this.ingredientsChanged.emit(this.ingredients.slice());
  }
}

Chain loading

index.html > main.ts > app.module.ts > app.component.ts

Lifecycle

  1. ngOnInit //once the component is initialized
  2. constructor()
  3. ngOnChanges //after a bound input property change
  4. ngDoCheck //every change detenction run
  5. ngOnDestroy onece the component is about to be destroyed

imports

@angular/core

  • Component

@angular/forms

  • FormsModuel

install bootstrap

npm install --save bootstrap

//.angular-cli.json
"styles":[
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
  "style.css"
]

toggle value

<button (click)="isTrue = !isTrue">

check if @input change

ngOnChange(changes:SimpleChanges){
	//..
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment