Angular Components¶
General¶
Create a component:
ng generate component <component-name>
import { Component } from "@angular/core";
@Component({
selector: "hello-world",
templateUrl: "hello-world.component.html",
styleUrls: ["hello-world.component.css"],
})
export class HelloWorldComponent {
// The code in this class drives the component's behavior.
}
<h2>Hello World</h2>
<p>This is my first component!</p>
<p class="a">Hello!</p>
.component.css
h2 {
color: blue;
}
.a {
margin: 10px;
}
other.component.html
<app-hello-world></app-hello-world>
Interpolation¶
import { Component } from "@angular/core";
@Component({
selector: "hello-world-interpolation",
templateUrl: "./hello-world-interpolation.component.html",
})
export class HelloWorldInterpolationComponent {
message = "Hello, World!";
}
<h2>{{ message }}</h2>
<h2>Hello, World!</h2>
Data Pipes¶
Pipe | Description |
---|---|
DatePipe |
formats a date value |
UpperCasePipe |
transforms text to upper case |
LowerCasePipe |
transforms text to lower case |
CurrencyPipe |
formats a number as currency |
DecimalPipe |
formats a number as decimal |
PercentPipe |
formats a number as percent |
import { Component } from "@angular/core";
@Component({
selector: "hello-world-pipes",
templateUrl: "./hello-world-pipes.component.html",
})
export class HelloWorldPipesComponent {
today = new Date();
price = 1.23;
percent = 0.456;
}
<h2>{{ today | date }}</h2>
<p>{{ price | currency }}</p>
<p>{{ percent | percent }}</p>
<h2>2021-03-01</h2>
<p>$1.23</p>
<p>45.6%</p>
Custom Data Pipes¶
ng generate pipe <pipe-name>
pipe-name.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'exponentialStrength})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent = 1): number {
return Math.pow(value, exponent);
}
}
Property Binding¶
...
export class HelloWorldBindingsComponent {
fontColor = 'blue';
sayHelloId = 1;
}
<p
[id]="sayHelloId"
[style.color]="fontColor">
You can set color in the component!
</p>
Event Binding¶
...
export class HelloWorldBindingsComponent {
canClick = false;
message = 'Hello, World';
sayMessage() {
alert(this.message);
}
}
<button
type="button"
[disabled]="canClick"
(click)="sayMessage()">
Trigger alert message
</button>