响应式

声明状态

Angular 标志 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 {}

Marko 标志 Marko

<let/name="张三">
<h1>你好 ${name}</h1>

更新状态

Angular 标志 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 {}

Marko 标志 Marko

<let/name="张三">
<script>name = "李四"</script>
<h1>你好 ${name}</h1>

计算属性

Angular 标志 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 {}

Marko 标志 Marko

<let/count=10>
<const/doubleCount=count * 2>
<div>${doubleCount}</div>

模板语法

最简模板

Angular 标志 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 {}

Marko 标志 Marko

<h1>你好,世界</h1>

样式

Angular 标志 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 {}

Marko 标志 Marko

<h1.title>我是红色的</h1>
<button style={ "font-size": "10rem" }>我是一个按钮</button>
<button class=scopedButton>我是一个样式作用域按钮</button>

<style>
  .title {
    color: red;
  }
</style>
<style/{ scopedButton }>
  .scopedButton {
    font-size: 10rem;
  }
</style>

DOM循环

Angular 标志 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 {}

Marko 标志 Marko

<ul>
  <for|color| of=["红", "绿", "蓝"]>
    <li>${color}</li>
  </for>
</ul>

点击事件

Angular 标志 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 {}

Marko 标志 Marko

<let/count=0>
<p>计数器: ${count}</p>
<button onClick() { count++ }>+1</button>

DOM引用

Angular 标志 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 {}

Marko 标志 Marko

<input/inputElement>
<script>
  inputElement().focus();
</script>

条件渲染

Angular 标志 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 {}

Marko 标志 Marko

static const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
<let/lightIndex=0>
<const/light=TRAFFIC_LIGHTS[lightIndex]>

<button onClick() { lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length }>
  下一个灯
</button>
<p>现在亮着的是: ${light}</p>
<p>
  你应该
  <if=light === "红灯">停下</if>
  <else if=light === "黄灯">慢行</else>
  <else>赶紧走</else>
</p>

生命周期

组件加载时

Angular 标志 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 {}

Marko 标志 Marko

<let/pageTitle="">
<script>pageTitle = document.title</script>
<p>页面标题: ${pageTitle}</p>

组件卸载时

Angular 标志 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 {}

Marko 标志 Marko

<let/time=new Date()>
<script>
  const id = setInterval(() => time = new Date(), 1000);
  $signal.onabort = () => clearInterval(id)
</script>
<p>当前时间: ${time.toLocaleTimeString()}</p>

组件组合

组件Props传参

Angular 标志 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 {}

Marko 标志 Marko

<UserProfile
  name="张三"
  age=20
  favouriteColors=["green", "blue", "red"]
  isAvailable
/>

向父组件emit事件

Angular 标志 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 {}

Marko 标志 Marko

<let/isHappy=true>
<p>你快乐吗?</p>
<AnswerButton
  onYes() { isHappy = true }
  onNo() { isHappy = false }
/>
<p style={ "font-size": 50 }>${isHappy ? "😀" : "😥"}</p>

slot插槽

Angular 标志 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 {}

Marko 标志 Marko

<FunnyButton>点我!</FunnyButton>

slot插槽内容

Angular 标志 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 {}

Marko 标志 Marko

<FunnyButton/>
<FunnyButton>这是传到slot的内容!</FunnyButton>

上下文

Angular 标志 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 {}

Marko 标志 Marko

<let/user={
  id: 1,
  username: "abcdefg",
  email: "[email protected]",
}>
<const/updateUsername(newUsername) {
  user = { ...user, username: newUsername };
}>

<h1>欢迎回来, ${user.username}</h1>
<context={ ...user, updateUsername }>
  <UserProfile />
</context>

表单输入

输入框

Angular 标志 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 {}

Marko 标志 Marko

<let/text="你好世界">
<p>${text}</p>
<input value:=text>

复选框

Angular 标志 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 {}

Marko 标志 Marko

<input#is-available
  type="checkbox"
  checked:=input.isAvailable
>
<label for="is-available">这是一个checkbox</label>

单选框

Angular 标志 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 {}

Marko 标志 Marko

<let/picked="red">

<div>你选择了: ${picked}</div>
<input#blue-pill
  type="radio"
  value="blue"
  checkedValue:=picked
>
<label for="blue-pill">蓝色</label>

<input#red-pill
  type="radio"
  value="red"
  checkedValue:=picked
>
<label for="red-pill">红色</label>

选择器

Angular 标志 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 {}

Marko 标志 Marko

static const colors = [
  { id: 1, text: "红" },
  { id: 2, text: "蓝" },
  { id: 3, text: "绿" },
  { id: 4, text: "灰", isDisabled: true },
];
<let/selectedColorId=2>

<select value:=selectedColorId>
  <for|{ id, isDisabled, text }| of=colors>
    <option value=id disabled=isDisabled>
      ${text}
    </option>
  </for>
</select>

Web应用特性

渲染应用

Angular 标志 Angular

<!doctype html>
<html>
  <body>
    <app-root></app-root>
  </body>
</html>

Marko 标志 Marko

<!doctype html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./app.js"></script>
  </body>
</html>

fetch获取数据

Angular 标志 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;
  };
}

Marko 标志 Marko

<try>
  <await|{ results: users }|=fetch("https://randomuser.me/api/?results=3").then(res => res.json())>
    <ul>
      <for|{ picture, name }| of=users>
        <li>
          <img src=picture.thumbnail alt="user">
          <p>${name.first} ${name.last}</p>
        </li>
      </for>
    </ul>
  </await>
  <@placeholder>
    <p>正在获取用户信息……</p>
  </@placeholder>
  <@catch|error|>
    <p>获取用户信息出错</p>
  </@catch>
</try>