响应式
声明状态
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-name",
template: `<h1>你好 {{ name }}</h1>`,
})
export class NameComponent {
name = "张三";
}
@NgModule({
declarations: [NameComponent],
exports: [NameComponent],
})
export class NameModule {}
更新状态
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-name",
template: `<h1>你好 {{ name }}</h1>`,
})
export class NameComponent {
name = "张三";
constructor() {
this.name = "李四";
}
}
@NgModule({
declarations: [NameComponent],
exports: [NameComponent],
})
export class NameModule {}
计算属性
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-doublecount",
template: `<div>{{ doubleCount }}</div>`,
})
export class DoublecountComponent {
count = 10;
get doubleCount() {
return this.count * 2;
}
}
@NgModule({
declarations: [DoublecountComponent],
exports: [DoublecountComponent],
})
export class DoublecountModule {}
模板语法
最简模板
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-helloworld",
template: `<h1>你好,世界</h1>`,
})
export class HelloworldComponent {}
@NgModule({
declarations: [HelloworldComponent],
exports: [HelloworldComponent],
})
export class HelloworldModule {}
样式
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-cssstyle",
template: `
<h1 class="title">我是红色的</h1>
<button style="font-size: 10rem">我是一个按钮</button>
`,
styles: [
`
.title {
color: red;
}
`,
],
})
export class CssStyleComponent {}
@NgModule({
declarations: [CssStyleComponent],
exports: [CssStyleComponent],
})
export class CssStyleModule {}
DOM循环
Angular
import { Component, NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
@Component({
selector: "app-colors",
template: `
<ul>
<li *ngFor="let color of colors">{{ color }}</li>
</ul>
`,
})
export class ColorsComponent {
colors = ["红", "绿", "蓝"];
}
@NgModule({
declarations: [ColorsComponent],
imports: [CommonModule],
exports: [ColorsComponent],
})
export class ColorsModule {}
点击事件
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-counter",
template: `
<p>计数器: {{ count }}</p>
<button (click)="incrementCount()">+1</button>
`,
})
export class CounterComponent {
count = 0;
incrementCount() {
this.count++;
}
}
@NgModule({
declarations: [CounterComponent],
exports: [CounterComponent],
})
export class CounterModule {}
DOM引用
Angular
import {
Component,
ViewChild,
ElementRef,
OnInit,
NgModule,
} from "@angular/core";
@Component({
selector: "app-inputfocused",
template: `<input type="text" #inputRef />`,
})
export class InputfocusedComponent implements OnInit {
@ViewChild("inputRef", { static: true })
inputRef!: ElementRef<HTMLInputElement>;
ngOnInit() {
this.inputRef.nativeElement.focus();
}
}
@NgModule({
declarations: [InputfocusedComponent],
exports: [InputfocusedComponent],
})
export class InputfocusedModule {}
条件渲染
Angular
import { Component, NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
@Component({
selector: "app-trafficlight",
template: `
<button (click)="nextLight()">下一个灯</button>
<p>现在亮着的是: {{ light }}</p>
<p>
你应该
<ng-container [ngSwitch]="light">
<span *ngSwitchCase="'红灯'">停下</span>
<span *ngSwitchCase="'黄灯'">慢行</span>
<span *ngSwitchCase="'绿灯'">赶紧走</span>
</ng-container>
</p>
`,
})
export class TrafficlightComponent {
lightIndex = 0;
get light() {
return TRAFFIC_LIGHTS[this.lightIndex];
}
nextLight() {
this.lightIndex = (this.lightIndex + 1) % TRAFFIC_LIGHTS.length;
}
}
@NgModule({
declarations: [TrafficlightComponent],
imports: [CommonModule],
exports: [TrafficlightComponent],
})
export class TrafficlightModule {}
<div
x-data="{
TRAFFIC_LIGHTS: ['红灯', '黄灯', '绿灯'],
lightIndex: 0,
get light() { return this.TRAFFIC_LIGHTS[this.lightIndex] },
nextLight() {
this.lightIndex = (this.lightIndex + 1) % this.TRAFFIC_LIGHTS.length;
}
}"
>
<button x-on:click="nextLight">下一个灯</button>
<p>现在亮着的是: <span x-text="light"></span></p>
<p>
你应该
<span x-show="light === '红灯'">停下</span>
<span x-show="light === '黄灯'">慢行</span>
<span x-show="light === '绿灯'">赶紧走</span>
</p>
</div>
生命周期
组件加载时
Angular
import { Component, NgModule, OnInit } from "@angular/core";
@Component({
selector: "app-pagetitle",
template: `<p>页面标题: {{ pageTitle }}</p>`,
})
export class PagetitleComponent implements OnInit {
pageTitle = "";
ngOnInit() {
this.pageTitle = document.title;
}
}
@NgModule({
declarations: [PagetitleComponent],
exports: [PagetitleComponent],
})
export class PagetitleModule {}
组件卸载时
Angular
import { Component, NgModule, OnDestroy } from "@angular/core";
@Component({
selector: "app-time",
template: `<p>当前时间: {{ time }}</p>`,
})
export class TimeComponent implements OnDestroy {
time = new Date().toLocaleTimeString();
timer = setInterval(() => {
this.time = new Date().toLocaleTimeString();
}, 1000);
ngOnDestroy() {
clearInterval(this.timer);
}
}
@NgModule({
declarations: [TimeComponent],
exports: [TimeComponent],
})
export class TimeModule {}
组件组合
组件Props传参
Angular
import { Component, NgModule } from "@angular/core";
import { UserprofileModule } from "./userprofile.component";
@Component({
selector: "app-root",
template: `
<app-userprofile
name="张三"
[age]="20"
[favouriteColors]="['green', 'blue', 'red']"
[isAvailable]="true"
>
</app-userprofile>
`,
})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
imports: [UserprofileModule],
bootstrap: [AppComponent],
})
export class AppModule {}
<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->
<div
x-data="{
name: '张三',
age: 20,
favouriteColors: ['green', 'blue', 'red'],
isAvailable: true
}"
>
<p>我的名字是 <span x-text="张三"></span></p>
<p>My age is <span x-text="age"></span></p>
<p>
My favourite colors are <span x-text="favouriteColors.join(', ')"></span>
</p>
<p>I am <span x-text="isAvailable ? 'available' : 'not available'"></span></p>
</div>
向父组件emit事件
Angular
import { Component, NgModule } from "@angular/core";
import { AnswerButtonModule } from "./answer-button.component";
@Component({
selector: "app-root",
template: `
<p>你快乐吗?</p>
<app-answer-button (yes)="onAnswerYes()" (no)="onAnswerNo()">
</app-answer-button>
<p style="font-size: 50px">{{ isHappy ? "😀" : "😥" }}</p>
`,
})
export class AppComponent {
isHappy = true;
onAnswerYes() {
this.isHappy = true;
}
onAnswerNo() {
this.isHappy = false;
}
}
@NgModule({
declarations: [AppComponent],
imports: [AnswerButtonModule],
bootstrap: [AppComponent],
})
export class AppModule {}
slot插槽
Angular
import { Component, NgModule } from "@angular/core";
import { FunnyButtonModule } from "./funny-button.component";
@Component({
selector: "app-root",
template: `<app-funny-button>点我!</app-funny-button>`,
})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
imports: [FunnyButtonModule],
bootstrap: [AppComponent],
})
export class AppModule {}
<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->
<button
x-data
x-text="'点我!'"
style="
background: rgba(0, 0, 0, 0.4);
color: #fff;
padding: 10px 20px;
font-size: 30px;
border: 2px solid #fff;
margin: 8px;
transform: scale(0.9);
box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
outline: 0;
"
>
<span>默认slot内容</span>
</button>
slot插槽内容
Angular
import { Component, NgModule } from "@angular/core";
@Component({
selector: "app-root",
template: `
<app-funny-button></app-funny-button>
<app-funny-button>
<ng-template #content>这是传到slot的内容!</ng-template>
</app-funny-button>
`,
})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
imports: [FunnyButtonModule],
bootstrap: [AppComponent],
})
export class AppModule {}
<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->
<button
x-data
style="
background: rgba(0, 0, 0, 0.4);
color: #fff;
padding: 10px 20px;
font-size: 30px;
border: 2px solid #fff;
margin: 8px;
transform: scale(0.9);
box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
outline: 0;
"
>
<span>默认slot内容</span>
</button>
<button
x-data
x-text="'这是传到slot的内容!'"
style="
background: rgba(0, 0, 0, 0.4);
color: #fff;
padding: 10px 20px;
font-size: 30px;
border: 2px solid #fff;
margin: 8px;
transform: scale(0.9);
box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
outline: 0;
"
>
<span>默认slot内容</span>
</button>
上下文
Angular
import { Component, NgModule } from "@angular/core";
import { UserService } from "./user.service";
import { UserProfileModule } from "./user-profile.component";
@Component({
providers: [UserService],
selector: "app-root",
template: `
<h1>欢迎回来, {{ userService.user.username }}</h1>
<app-user-profile />
`,
})
export class AppComponent {
constructor(public userService: UserService) {}
}
@NgModule({
declarations: [AppComponent],
imports: [UserProfileModule],
bootstrap: [AppComponent],
})
export class AppModule {}
<!-- x-text 必须用在带有 x-data 的元素或其子元素上。 -->
<!-- 这两个元素可以共用一个带有 x-data 的父元素,也可以像下面这样分别添加 x-data: -->
<h1 x-data>
欢迎回来, <span x-text="$store.user.username">未知用户</span>
</h1>
<div x-data>
<h2>我的简介</h2>
<p>用户名: <span x-text="$store.user.username"></span></p>
<p>邮箱: <span x-text="$store.user.email"></span></p>
<button @click="$store.user.updateUsername('李四')">
更新用户名为 李四
</button>
</div>
<script>
document.addEventListener("alpine:init", () => {
Alpine.store("user", {
id: 1,
username: "abcdefg",
email: "[email protected]",
updateUsername(newUsername) {
this.username = newUsername;
},
});
});
</script>
表单输入
输入框
Angular
import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
@Component({
selector: "app-input-hello",
template: `
<p>{{ text }}</p>
<input [(ngModel)]="text" />
`,
})
export class InputHelloComponent {
text = "";
}
@NgModule({
declarations: [InputHelloComponent],
imports: [FormsModule],
exports: [InputHelloComponent],
})
export class InputHelloModule {}
复选框
Angular
import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
@Component({
selector: "app-is-available",
template: `
<input id="is-available" type="checkbox" [(ngModel)]="isAvailable" />
<label for="is-available">这是一个checkbox</label>
`,
})
export class IsAvailableComponent {
isAvailable = false;
}
@NgModule({
declarations: [IsAvailableComponent],
imports: [FormsModule],
exports: [IsAvailableComponent],
})
export class IsAvailableModule {}
单选框
Angular
import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
@Component({
selector: "app-pick-pill",
template: `
<div>你选择了: {{ picked }}</div>
<input id="blue-pill" type="radio" value="blue" [(ngModel)]="picked" />
<label for="blue-pill">蓝色</label>
<input id="red-pill" type="radio" value="red" [(ngModel)]="picked" />
<label for="red-pill">红色</label>
`,
})
export class PickPillComponent {
picked = "red";
}
@NgModule({
declarations: [PickPillComponent],
imports: [FormsModule],
exports: [PickPillComponent],
})
export class PickPillModule {}
选择器
Angular
import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
@Component({
selector: "app-color-select",
template: `
<select [(ngModel)]="selectedColorId">
<option
*ngFor="let color of colors"
[value]="color.id"
[disabled]="color.isDisabled"
>
{{ color.text }}
</option>
</select>
`,
})
export class ColorSelectComponent {
selectedColorId = 2;
colors = [
{ id: 1, text: "红" },
{ id: 2, text: "蓝" },
{ id: 3, text: "绿" },
{ id: 4, text: "灰", isDisabled: true },
];
}
@NgModule({
declarations: [ColorSelectComponent],
imports: [FormsModule],
exports: [ColorSelectComponent],
})
export class ColorSelectModule {}
<div
x-data="{
selectedColorId: 2,
colors: [
{ id: 1, text: '红' },
{ id: 2, text: '蓝' },
{ id: 3, text: '绿' },
{ id: 4, text: '灰', isDisabled: true }
]
}"
>
<select x-model.number="selectedColorId">
<template x-for="color in colors" x-bind:key="color.id">
<option
x-text="color.text"
x-bind:value="color.id"
x-bind:disabled="!!color.isDisabled"
x-bind:selected="color.id === selectedColorId"
></option>
</template>
</select>
</div>
Web应用特性
渲染应用
fetch获取数据
Angular
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
export interface UsersState {
users: User[];
error: string | null;
loading: boolean;
}
export const initialState: UsersState = {
users: [],
error: null,
loading: false,
};
@Injectable({ providedIn: "root" })
export class UserService {
private state = new BehaviorSubject<UsersState>(initialState);
state$ = this.state.asObservable();
constructor(private http: HttpClient) {}
loadUsers() {
this.state.next({ ...initialState, loading: true });
this.http
.get<UserResponse>("https://randomuser.me/api/?results=3")
.subscribe({
next: ({ results }) =>
this.state.next({ ...initialState, users: results }),
error: (error) => this.state.next({ ...initialState, error }),
});
}
}
export interface UserResponse {
results: User[];
info: any;
}
export interface User {
name: {
title: string;
first: string;
last: string;
};
picture: {
large: string;
medium: string;
thumbnail: string;
};
}
<div
x-data="
function fetchUsers() {
return {
users: null,
isLoading: false,
error: null,
async init() {
this.isLoading = true;
try {
this.users = (await (await fetch('https://randomuser.me/api/?results=3')).json()).results;
} catch (err) {
this.users = [];
this.error = err
}
this.isLoading = false;
},
};
}
"
>
<template x-if="isLoading">
<p>正在获取用户信息……</p>
</template>
<template x-if="error">
<p>获取用户信息出错</p>
</template>
<template x-if="!error">
<ul>
<template x-for="user in users">
<li>
<img
:src="user.picture.thumbnail"
:alt="`picture of ${user.name.first} ${user.name.last}`"
/>
<p x-text="`${user.name.first} ${user.name.last}`"></p>
</li>
</template>
</ul>
</template>
</div>