---
url: /guide/development/native-ui-with-angular.md
---

# 使用 Angular 构建界面

本指南详细阐述如何使用 Angular 前端框架开发 Nexus 应用的 Native UI 界面。

## 项目结构

在创建应用时，选择   `Angular Native UI`   模板，系统将自动生成标准的目录结构。所有前端资源存放于   `/web`   目录下，默认包含一个名为 `main`  的示例应用。入口文件将被作为 `Native UI` 模块资源加载至应用中。

典型目录结构示例如下：

```
my-first-app
├── src/
│   ├── resolvers/
│   │   └── index.ts
│   └── index.ts
├── web/
│   └── main/
│       ├── app.html
│       ├── app.ts
│       ├── index.ts
│       └── tsconfig.json
├── manifest.yaml
├── package.json
└── tsconfig.json
```

在 `web/main/index.ts` 中通过 `bootstrapNexusApplication`  启动应用：

```typescript
import { bootstrapNexusApplication } from "@pc-nexus/angular";
import { App } from "./app";

bootstrapNexusApplication(App);
```

## 调用服务端函数

在 `app.ts`  文件中编写业务逻辑，通过 `invoke`  方法调用服务端解析器函数：

```typescript
import { Component, signal } from "@angular/core";
import { invoke } from "@pc-nexus/bridge";
import { NxText } from "@pc-nexus/angular";

@Component({
  selector: "app-root",
  templateUrl: "./app.html",
  imports: [NxText],
})
export class App {
  protected readonly result = signal<string | null>(null);

  constructor() {
    this.runGreeting();
  }

  protected runGreeting() {
    invoke<string, string>("greeting", "Nexus")
      .then((res: string) => this.result.set(res))
      .catch((err: Error) => this.result.set(`Error: ${err}`));
  }
}
```

## 前端界面展示

在 `app.html`  模板中使用 `@pc-nexus/angular` 组件绑定数据，渲染服务端返回的内容：

```xml
<nx-text>{{ result() }}</nx-text>
```

## 配置资源

在 `manifest.yaml`  中把 `path`  指向入口文件，并设置 `render: native` 。部署时无需手动构建前端， `CLI` 会通过   `angular-builder`  自动打包：

```yaml
resources:
  - key: main
    path: web/main/index.ts
    render: native
```

## 事件绑定

在模板中通过 `(event)`  绑定事件，用法与普通 `Angular` 一致：

```xml
<nx-text>{{ count() }}</nx-text>
<nx-button color="primary" (click)="onClick()">click ++</nx-button>
```

```typescript
protected readonly count = signal(0)

protected onClick(): void {
  this.count.update((value) => value + 1)
}
```

更多事件用法见： [Native UI 事件](/reference/interface/ui-components/events) 。

## Hooks 的使用

`@pc-nexus/angular` 提供与 `Bridge` 集成的 `Hooks` ，可在组件中直接调用。

## 样式绑定

通过 `class`  绑定样式，传入白名单内的工具类即可：

```xml
<nx-box class="p-3 flex align-items-center">
  <nx-text class="mr-2">Hello Nexus</nx-text>
</nx-box>
```

可用工具类见： [Native UI 样式白名单](/reference/interface/ui-components/styles) 。

## 限制

* **只用平台组件** ：请使用 `@pc-nexus/angular` 导出的组件（如 `nx-button` 、 `nx-text` ）；不要使用 `div` 、 `span` 等原生标签，也不要写其它任意 HTML。
* **自定义组件可以写，但只当容器** ：Angular 自定义组件的标签本身不会出现在最终界面里（会被自动去掉），里面的子内容会保留；因此不要在自定义组件标签上绑事件或 `class` 。
* **事件和样式走白名单** ：只有平台支持的事件、工具类 `class` 才会生效；白名单之外的会被忽略。
