In本教程中,我们将从新建一个 Angular app and transition into the native mobile app realm using Capacitor. You can also add Capgo Native Navigation and Transitions for a native mobile feel, and use tailwind-capacitor for safe areas.
Capacitor allows you to easily convert your Angular web application into a native mobile app without requiring significant modifications or learning a new skill like React Native.
CapacitorJS
This tutorial will guide you through the process, starting with a new Angular app and then incorporating Capacitor to move into the realm of native mobile apps. You can also use Capgo Native Navigation, Transitions, and tailwind-capacitor for safe areas.
About Capacitor
CapacitorJS
With Capacitor, you get a fantastic native mobile app without any complicated setup or steep learning curve. Its slim API and streamlined functionality make it a breeze to integrate into your project. Trust me, you’ll be amazed at how effortless it is to achieve a fully functional native app with Capacitor!
CapacitorJS
CapacitorJS
ng new my-app
cd my-app
选择“Angular”时,请选择Angular版本。
为了创建一个原生移动应用,我们需要一个 export 项目的 我们的项目中包含一个简单的脚本,用于在package.json中构建和复制Angular项目: 执行命令后,您应该能够在项目根目录看到一个新的
{
"scripts": {
// ...
"build": "ng build --prod"
}
}
文件夹。 build此文件夹将由__CAPGO_KEEP_0__稍后使用,但现在我们必须正确设置它。 dist 将__CAPGO_KEEP_0__添加到Angular应用中
This folder will be used by Capacitor later on, but for now, we must set it up correctly.
Adding Capacitor to Your Angular App
完成 sync 命令。
首先,我们可以安装 Capacitor CLI 接下来,我们需要安装核心包和iOS和Android平台的相关包。
最后,我们可以添加平台,
Finally, we can add the platforms, and Capacitor will create folders for each platform at the root of our project:
# Install the Capacitor CLI locally
npm install -D @capacitor/cli
# Initialize Capacitor in your Angular project
npx cap init
# Install the required packages
npm install @capacitor/core @capacitor/ios @capacitor/android
# Add the native platforms
npx cap add ios
npx cap add android
和 文件夹。 这些是真正的本机项目! android folders in your Angular project.
Those are real native projects!
To access the Android project later, you must install Android StudioFor iOS, you need a Mac and should install Xcode.
Additionally, you should find a capacitor.config.ts file in your project, which contains some fundamental Capacitor settings utilized during the sync. The only thing you need to pay attention to is the webDircontext: HTML text fragment from a longer Capgo UI string (parent key `solutions_cordova_to_capacitor_ai_step2_body`). Page/area: Capgo solutions marketing page. Role: Website copy sentence. Seen in: page solutions/cordova-to-capacitor-ai.astro. Message key `solutions_cordova_to_capacitor_ai_step2_body` (Solutions Cordova To Capacitor Ai Step2 Body).
, which must point to the result of your build command. Currently, it is inaccurate. capacitor.config.json __CAPGO_KEEP_0__.config.json webDir:
{
"appId": "com.example.app",
"appName": "my-app",
"webDir": "dist"
}
您可以通过执行以下命令来尝试它:
npm run build
npx cap sync
第一个命令 npm run build 将仅仅构建您的Angular项目并复制静态构建,而第二个命令 npx cap sync 将同步所有的web code 到native平台的正确位置,以便它们可以在应用中显示。
此外,同步命令可能会更新native平台并安装插件,因此当您安装一个新的 Capacitor 插件 npx cap sync 时,需要重新运行
命令。
没有注意到,您现在实际上已经完成了,所以让我们在设备上看到应用!
构建和部署原生应用程序需要 Xcode 已安装,并且对于 Android 应用,您需要安装 Android Studio 已安装。另外,如果您打算在应用商店上发布您的应用,则需要在 iOS 上注册 Apple Developer Program,在 Android 上注册 Google Play Console。
如果您是新手,native mobile 开发,您可以使用 Capacitor CLI 来轻松打开两个 native 项目:
npx cap open ios
npx cap open android
一旦您设置了 native 项目,部署应用到连接设备就很容易了。在 Android Studio 中,只需等待所有内容就绪,然后您可以在不更改任何设置的情况下将应用部署到连接设备。以下是示例:

在 Xcode 中,您需要设置签名账户才能将应用部署到真实设备,而不是仅仅在模拟器上。 如果您之前没有这样做过,Xcode 会指导您完成此过程(但请再次注意,您必须注册开发者计划)。随后,您只需点击播放即可在连接设备上运行应用,您可以在顶部选择设备。以下是示例:

恭喜!您已成功将 Angular web 应用部署到移动设备。以下是示例:
但请稍等,有更快的方法可以在开发期间完成此操作…
Capacitor 实时重载
到目前为止,你可能已经习惯了所有现代框架都具有热重载的功能,而好消息是你可以在移动设备上实现相同的功能 在移动设备上 只需花费最少的努力
通过实时重载,允许你在本地主机上访问你的应用 在你的网络上 通过让 Capacitor 应用从特定的 URL 加载内容
第一步是确定你的本地 IP 地址。如果你使用的是 Mac,通过在终端中运行以下命令可以找到它
ipconfig getifaddr en0
在 Windows 上运行:
ipconfig
然后查找 IPv4 地址
我们可以通过在我们的文件中添加另一个条目来指示 Capacitor 直接从服务器加载应用 capacitor.config.ts 文件
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'my-app',
webDir: 'dist',
bundledWebRuntime: false,
server: {
url: 'http://192.168.x.xx:4200',
cleartext: true
}
};
export default config;
请确保使用 正确的IP和端口,我在这个例子中使用了默认的Angular端口。
现在,我们可以将这些更改应用到我们的原生项目中:
npx cap copy
命令与 copy 类似,但它只会 sync将web文件夹和配置中的更改复制到原生项目中,而不更新原生项目。 您现在可以通过Android Studio或Xcode再次部署您的应用。之后,如果您在Angular应用中更改了什么 应用将自动重新加载
并显示更改! items text
请注意 如果您安装了新插件,如摄像头插件,它仍然需要重新构建您的原生项目。这是因为原生文件已更改,无法在飞行中完成。
请注意,您应该在配置中使用正确的IP和端口。上面的code块显示了用于演示目的的Angular默认端口。
使用Capacitor插件
让我们看看如何在实际操作中使用一个Capacitor插件,我们之前提到过几次。要做到这一点,我们可以通过运行以下命令安装一个相当简单的插件:
npm i @capacitor/share
没有什么特别的关于 分享插件,但它仍然会弹出原生分享对话框!为了实现这一点,我们现在只需要导入包并从我们的应用中调用相应的 share() 函数,所以让我们修改 src/app/app.component.ts 到这个:
import { Component } from '@angular/core';
import { Share } from '@capacitor/share';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'my-app';
async share() {
await Share.share({
title: 'Open Youtube',
text: 'Check new video on youtube',
url: 'https://www.youtube.com',
dialogTitle: 'Share with friends'
});
}
}
如前所述,当安装新插件时,我们需要执行同步操作,然后重新部署应用到设备上。要实现这一点,请运行以下命令:
npx cap sync
点击按钮后,您可以看到美丽的原生分享对话框在行动!
接下来,您可以让应用在iOS和Android上感觉更原生,使用Capgo导航和过渡,并修复常见的iOS布局问题,例如水平溢出或裁剪安全区域。
Native-feeling UI with Capgo Native Navigation and Transitions
我已经工作了几年 Ionic 来构建跨平台应用,但将其与Angular集成是hacky且罕见值得的,尤其是当您已经有 Tailwind CSS.
在Angular + Capacitor应用中实现原生移动感受的最佳方式是使用Capgo插件,而不是像Konsta UI这样的仅限Web UI套件:
- @capgo/capacitor-native-navigation ——原生导航栏、Liquid Glass iOS标签栏和Android模糊标签栏样式。您的Angular路由器保留路由状态;插件拥有原生浏览器。
- @capgo/capacitor-transitions ——在WebView层中实现Ionic样式页面过渡和iOS边缘滑动返回,且不采用Ionic UI。
安装两者:
bun add @capgo/capacitor-native-navigation @capgo/capacitor-transitions
bunx cap sync
配置原生导航以使用 CSS inset 模式,使 Web 内容尊严原生导航条:
import { NativeNavigation } from '@capgo/capacitor-native-navigation';
await NativeNavigation.configure({
contentInsetMode: 'css',
animationDuration: 360,
glass: {
effect: 'liquidGlass',
},
});
渲染液态玻璃标签栏(iOS 使用系统所有权渲染;Android 使用模糊 WebView 背景):
import { inject } from '@angular/core';
import { Router } from '@angular/router';
const router = inject(Router);
await NativeNavigation.setTabbar({
selectedId: 'home',
labelVisibilityMode: 'labeled',
icons: true,
colors: { dynamic: true },
tabs: [
{ id: 'home', title: 'Home', icon: { svg: '...' } },
{ id: 'settings', title: 'Settings', icon: { svg: '...' } },
],
});
await NativeNavigation.addListener('tabSelect', ({ id }) => {
router.navigate([`/${id}`]);
});
Add native page transitions in your app shell:
```typescript
// app.component.ts
import { Component, CUSTOM_ELEMENTS_SCHEMA, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
import '@capgo/capacitor-transitions';
import { initTransitions, setDirection, setupRouterOutlet } from '@capgo/capacitor-transitions';
initTransitions({ platform: 'auto' });
@Component({
selector: 'app-root',
schemas: [CUSTOM_ELEMENTS_SCHEMA],
template: `
<cap-router-outlet #outlet platform="auto" swipe-gesture="auto">
<router-outlet></router-outlet>
</cap-router-outlet>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('outlet') outlet?: ElementRef<HTMLElement>;
constructor(private router: Router) {}
ngAfterViewInit() {
if (this.outlet?.nativeElement) {
setupRouterOutlet(this.outlet.nativeElement, { platform: 'auto', swipeGesture: 'auto' });
}
}
openSettings() {
setDirection('forward');
this.router.navigate(['/settings']);
}
}
Wrap routed 页面在 cap-router-outlet, cap-page,并 cap-content,并调用 setDirection('forward') 或 setDirection('back') context
在导航之前进行。不要在原生导航拥有这些表面时重复 Web 头部或底部。 Using @capgo/capacitor-native-navigation 使用 @__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-native-navigation Using @capgo/capacitor-transitions.
安全区域与Tailwind
在Tailwind CSS中,使用设备安全区域 @capgo/tailwind-capacitor 发布于 tailwind-capacitor 在npm上发布。它提供 safe-areas 工具和其他Capacitor友好的Tailwind插件:
bun add -D tailwind-capacitor
在 src/styles.css:
@import 'tailwindcss';
@plugin "@capgo/tailwind-capacitor/platform";
@plugin "@capgo/tailwind-capacitor/safe-areas";
使用工具,如 pt-safe, pb-safe, px-safe 而不是手动添加 env(safe-area-inset-*) 。该项目正在积极开发中——如果您的Angular设置缺少某些内容,请在__CAPGO_KEEP_0__上打开一个PR open a PR on GitHub.
解决 iOS 布局问题 (视口、安全区域和水平溢出)
如果 iOS 内容看起来被裁剪、偏移或水平滚动,仅添加或调整视口标签通常无法解决问题。按照以下检查顺序进行工作。 overflow-x: hidden 确保视口元标签正确应用
在
,将视口元标签设置在 src/index.html正确处理 iOS 安全区域 <head>:
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
从根包装器中只处理一次安全区域
创建一个单独的应用 shell 并在其中应用安全区域填充 — 不要在多个嵌套组件中:
html,
body,
app-root {
width: 100%;
min-height: 100%;
margin: 0;
padding: 0;
overflow-x: hidden;
}
* {
box-sizing: border-box;
}
.app-shell {
min-height: 100dvh;
width: 100%;
padding-top: env(safe-area-inset-top);
padding-right: env(safe-area-inset-right);
padding-bottom: env(safe-area-inset-bottom);
padding-left: env(safe-area-inset-left);
}
将所有页面内容包装在 .app-shell.在头部、模态窗口和布局包装器中重复安全区域填充通常会使 UI 看起来被裁剪或过大。
使用 @capgo/tailwind-capacitor,您可以使用类似于 pt-safe pb-safe px-safe 在单个壳中
设置Capacitor iOS contentInset 到 never 首先
在 capacitor.config.ts,优先使用原生 inset 并让 CSS(或 Native Navigation 的) contentInsetMode: 'css')拥有安全区域:
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'my-app',
webDir: 'www',
ios: {
contentInset: 'never',
},
};
混合Capacitor的自动内容 inset 与 CSS env(safe-area-inset-*) padding 是双倍间距的常见原因。
找到真正溢出的元素
通常的凶手是使用 100vw在 Safari Web Inspector 中,运行: w-screen使用 Tailwind 替换 min-width.
使用
[...document.querySelectorAll('*')]
.filter(el => el.scrollWidth > document.documentElement.clientWidth)
.map(el => ({
el,
tag: el.tagName,
class: el.className,
scrollWidth: el.scrollWidth,
clientWidth: document.documentElement.clientWidth,
}));
当可能时。许多水平溢出问题来自 w-screen ,重复的安全区域填充,或者一个固定宽度的容器 —— 不是来自视口元标签本身。 w-full 结论 100vw / w-screen__CAPGO_KEEP_0__ 是一个基于现有 Web 项目构建原生应用的优秀选择,提供了一个简单的方式来共享 __CAPGO_KEEP_1__ 并保持一致的 UI。
并且,通过添加
Capacitor is an excellent option for building native applications based on an existing web project, offering a simple way to share code and maintain a consistent UI.
,您甚至可以更轻松地为您的应用添加实时更新,使您的用户始终能够访问最新的功能和 bug 修复。 Capgo,一个固定的像素宽度,或者一个大
如果您想学习如何将Capgo添加到您的Angular应用中,请查看下一篇文章:
继续Angular和Capacitor的Building Mobile Apps
如果您正在使用 Building Mobile Apps with Angular and Capacitor 来规划原生媒体和界面行为,连接它与 使用@capgo/capacitor-live-activities 为原生能力在使用@capgo/capacitor-live-activities中 @capgo/capacitor-live-activities 为实现细节在@capgo/capacitor-live-activities中 使用@capgo/capacitor-video-player 为原生能力在使用@capgo/capacitor-video-player中 @capgo/capacitor-video-player 为 @capgo/capacitor 视频播放器的实现细节 使用 @capgo/capacitor 原生导航 为使用 @capgo/capacitor 原生导航的原生能力