Common - deependhamecha/angular GitHub Wiki

To Create a component

  • Create a folder
  • Create a component file
import { Component } from '@angular/core';

@Component({
  selector: `my-c`,
  templateUrl: `./my-c.html`
})
export class MyComp {
  
}

and specify it in declarations

or

ng g c MyComp

Inline HTML

use template instead of templateUrl for inline.

Place Angular Component not via element but via attribute

<div my-c></div>
selector: '[my-c]'

Place Angular Component via class

<div class="my-c"></div>
selector: '.my-c'

Interpolation

{{variableName}}

Inner HTML

<p [innerText]="variableName"></p>

To Change Interpolation syntax

@Component(
  ...,
interpolation: [`[`, `]`]
)

Reserved interpolation characters

/^\s*$/
/[<>]/
/^[{}]$/
/&(#|[a-z])/i
/^\/\//

Event

<button (click)="methodName()">Click me</button>

methodName() {
  console.log("Clicked me");
}

If you want event object then pass $event to the argument list and event as the parameter.

You can cast the element target depending on the type of element.

(<HTMLInputElement>event.target).value;

Two way binding

[(ngModel)]="name"

In your module

imports: [FormsModule]

ngStyle

[ngStyle]="myStyle"
myStyle = {backgroundColor: "red"}
OR
myStyle = {backgroundColor: getColor()}

ngClass

.online {
  color: blue;
}
<p [ngClass]="{online: getBooleanValue()}">Dude</p>

ngFor

<my-c *ngFor="let myc of mycs"></my-c>
<p *ngFor="let a of array">{{a}}</p>

If you need index then *ngFor="let a of array; let i=index"

@Input

@Input takes in input.

@Input name: string;
<my-c name="'Deepen'" />

If you want to alias it, use @Input('myname') name: string; then <my-c myname="'Deepen'" />

@Output

@Output exports a value.

@Output getName: new EventEmitter<string>;
getName.emit(name+' Dhamecha');

Local Reference

<input type="text" [value]="name" (input)="changeName($event)" #mydude />
<i>{{mydude.value}}</i>

or you can also pass it to a method argument or you can also access directly from component using @ViewChild().

⚠️ **GitHub.com Fallback** ⚠️