填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

Angular 文件風格指南

Angular documentation style guide

本風格指南適用於那些為 Angular 文件(本站)做貢獻的人。所有作者都應遵循這些準則。違反之處必須由本文件的編輯批准。

This style guide is for anyone who contributes to the Angular documentation (this site). These guidelines should be followed by all authors. Deviations must be approved by a documentation editor.

這裡描述的指導原則有兩個目的:

The guidelines described here serve two purposes:

  • 確保為 Angular 文件使用者提供高品質,一致的體驗。

    To ensure a high-quality, consistent experience for Angular documentation users.

  • 簡化貢獻作者的寫作過程。本指南可幫助你做出關於語調、聲音和風格的決定。它還可以幫助你快速找到正確的標記(markup)。

    To simplify the writing process for contributing authors. This guide helps you make decisions about tone, voice, and style. It also helps you find the right markup quickly.

本指南是一份活檔案 ;它隨著時間而變化。我們力求在可行的範圍內保持一致性,但是你可能會發現我們的文件部分與這個風格指南不符。如有疑問,請遵循本指南,而不是模仿現有文件。

This guide is a living document; it changes over time. We strive for consistency to the extent feasible, but you may find parts of our documentation that don't match this style guide. When in doubt, follow this guide rather than imitating existing documents.

這些指導原則的範圍

Scope of these guidelines

我們要求所有撰文作者堅持以下三個方面:

We ask all contributing authors to adhere to three aspects of style:

  • 寫作風格:單詞用法,語法,大小寫和標點符號。堅持 Angular 的寫作指南可以確保一致的“聲音”,有助於確保資訊的準確性,並有助於不同背景的觀眾在世界範圍內使用。

    Writing style: Word usage, grammar, capitalization, and punctuation. Adherence to Angular's writing guidelines ensures a consistent "voice", helps ensure accuracy of the information, and facilitates use world-wide, by audiences with different backgrounds.

  • 標記風格:如何包含影象,表格,警告框和程式碼片段。Angular 文件是用 Markdown 編寫的,帶有該站點的自訂擴充套件。正確的標記確保了外觀的一致性,對於 doc 的正確建構和執行至關重要。

    Markup style: How to include images, tables, alert boxes, and code snippets. Angular docs are written in Markdown, with custom extensions for this site. Correct markup ensures a consistent look-and-feel, and is essential for the doc to build and function correctly.

  • Angular 的編碼風格:程式碼應用和程式碼片段的編碼風格。我們鼓勵使用程式碼範例示範如何應用所討論的概念和特性。Angular 有一個自訂框架,可讓作者直接從範例應用中包含程式碼片段,這些程式碼片段會作為 doc builds 的一部分進行自動測試。要提供程式碼範例程式碼,你必須要了解 Angular 本身以及 Angular doc examples 的自訂框架。

    Angular coding style: Coding style for example apps and code snippets. Code examples are encouraged for demonstrating how to apply the concepts and features discussed. Angular has a custom framework that enables authors to include code snippets directly from example apps that are automatically tested as part of doc builds. To contribute example code, you must understand Angular itself and the custom framework for Angular doc examples.

對於風格的每個方面,下表都解釋了在何處查詢主要指南以及 Angular Documentation Style Guide 提供的內容。

For each aspect of style, the following table explains where to find the primary guidelines and what this Angular Documentation Style Guide offers.

風格

Style

指南

Guidelines

寫作風格

Writing style

主要: Google Developer Documentation Style Guide

Primary: Google Developer Documentation Style Guide
This guide: Specifies any special considerations for Angular docs.

本指南:指定 Angular 文件的所有特殊注意事項。

標記風格

Markup style

小學:本指南

Primary: This guide
This guide: Specifies guidelines for markup of guides and tutorials, which are written primarily in Markdown.

本指南:指定指南和課程的標記指南,它們主要用 Markdown 編寫。

Angular 的編碼風格

Angular coding style

主要: Angular 風格指南

Primary: Angular Style Guide.
This guide: How to create, store, and include code examples in guides and tutorials.

本指南:如何在指南和課程中建立,儲存和包含程式碼範例。

注意:Angular API 和 CLI 參考文件都是從原始碼和/或相關的原始檔中產生的,這些檔案可能有其它的標記風格,還包括程式碼範例等。

Note: Angular API and CLI reference docs are generated from source code and/or related source files, which may have other markup styles and other ways of including code examples.

Doc 產生和工具

Doc generation and tooling

要修改文件頁面和範例程式碼,複製Angular 的 github 儲存函式庫,進入 aio/ 資料夾。

To make changes to the documentation pages and sample code, clone the Angular github repository and go to the aio/ folder.

aio / README.md解釋瞭如何安裝和使用這些工具編輯和測試你的更改。

The aio/README.md explains how to install and use the tools to edit and test your changes.

以下是指南頁面作者的一些基本命令。

Here are a few essential commands for guide page authors.

  1. yarn setup - 安裝包; build docs,stackblitz 和 zip。

    yarn setup — installs packages; builds docs, stackblitz, and zips.

  2. yarn docs-watch --watch-only - yarn docs-watch --watch-only 儲存的內容更改並重新整理瀏覽器。(可選)-- --watch-only 標誌跳過了初始的 docs rebuild。

    yarn docs-watch --watch-only — watches for saved content changes and refreshes the browser. The (optional) --watch-only flag skips the initial docs rebuild.

  3. yarn start - 啟動 doc viewer 應用,以便在瀏覽器中檢視本地更改。

    yarn start — starts the doc viewer application so you can see your local changes in the browser.

  4. http:// localhost:4200 / - 瀏覽到本地執行的應用。

    http://localhost:4200/ — browse to the app running locally.

你可以把 yarn docs-watchyarn start 成一個帶 yarn serve-and-sync 命令。

You can combine yarn docs-watch and yarn start into one command with yarn serve-and-sync.

指南頁面

Guide pages

除少量指南外,所有頁面都是帶有 .md 副檔名的markdown檔案。

All but a few guide pages are markdown files with an .md extension.

每個指南頁檔案都儲存在 content/guide 目錄下。雖然側面導航面板顯示為層次結構,但目錄是扁平的,沒有子資料夾。這種平面資料夾方法可以讓我們在不移動頁面檔案或重新導向舊頁面 URL 的情況下,改進明顯的導航結構。

Every guide page file is stored in the content/guide directory. Although the side navigation panel displays as a hierarchy, the directory is flat with no sub-folders. The flat folder approach allows us to shuffle the apparent navigation structure without moving page files or redirecting old page URLs.

doc 產生過程會使用 content/guide 目錄下的 markdown 檔案,並在 src/generated/docs/guide 目錄下產生 JSON 檔案,該目錄也是平的。這些 JSON 檔案包含文件元資料和 HTML 內容的組合。

The doc generation process consumes the markdown files in the content/guide directory and produces JSON files in the src/generated/docs/guide directory, which is also flat. Those JSON files contain a combination of document metadata and HTML content.

讀者可以透過網頁頁面的 URL 請求頁面。doc viewer 會抓取相應的 JSON 檔案並對其進行解釋,並把它渲染為一個完整格式的 HTML 頁面。

The reader requests a page by its Page URL. The doc viewer fetches the corresponding JSON file, interprets it, and renders it as fully-formed HTML page.

頁面 URL 會映象 content 檔案結構。指南頁面的網址是 guide/{page-name} “作者風采指南”的頁面位於 content/guide/docs-style-guide.md,它的 URL 是 guide/docs-style-guide

Page URLs mirror the content file structure. The URL for the page of a guide is in the form guide/{page-name}. The page for this "Authors Style Guide" is located at content/guide/docs-style-guide.md and its URL is guide/docs-style-guide.

課程頁和指南頁完全一樣。唯一的區別是它們駐留在 content/tutorial 而非 content/guide 並且擁有 tutorial/{page-name} 類別的 URL。

Tutorial pages are exactly like guide pages. The only difference is that they reside in content/tutorial instead of content/guide and have URLs like tutorial/{page-name}.

API頁面是從 Angular 原始碼產生到 src/generated/docs/api 目錄下的。doc viewer 會把那些以 api/ 開頭的 URL 轉換成該目錄下的 document JSON 檔案的請求。本風格指南中沒有討論 API 頁面的建立或維護。

API pages are generated from Angular source code into the src/generated/docs/api directory. The doc viewer translates URLs that begin api/ into requests for document JSON files in that directory. This style guide does not discuss creation or maintenance of API pages.

營銷頁面類似於指南頁面。它們位於 content/marketing 目錄中。雖然它們可以是 markdown 檔案,但它們可能是靜態 HTML 頁面,也可能是用 JSON 資料渲染的動態 HTML 頁面。

Marketing pages are similar to guide pages. They're located in the content/marketing directory. While they can be markdown files, they may be static HTML pages or dynamic HTML pages that render with JSON data.

只有少數人有權撰寫營銷頁面。本風格指南不討論營銷頁面的建立或維護。

Only a few people are authorized to write marketing pages. This style guide does not discuss creation or maintenance of marketing pages.

Markdown 和 HTML

Markdown and HTML

文件指南頁最終渲染為 HTML 格式,而且幾乎所有的頁面都用markdown格式編寫。

While documentation guide pages ultimately render as HTML, almost all of them are written in markdown.

Markdown 比 HTML 更容易閱讀和編輯。很多編輯器(包括 Visual Studio Code)都可以在你輸入的時候渲染 markdown。

Markdown is easier to read and to edit than HTML. Many editors (including Visual Studio Code) can render markdown as you type it.

你不時要退出降價促銷,並用 HTML 寫一部分文件。Markdown 允許你把 HTML 和 markdown 混合在一起。

From time to time you'll have to step away from markdown and write a portion of the document in HTML. Markdown allows you to mix HTML and markdown in the same document.

標準降價處理器不允許你把 HTML 標籤降價。但 Angular 文件降價處理器只要你遵循一條規則就支援 HTML 中的 markdown

Standard markdown processors don't allow you to put markdown within HTML tags. But the Angular documentation markdown processor supports markdown within HTML, as long as you follow one rule:

一定要用空行跟隨每個開啟和關閉的 HTML 標籤。

Always follow every opening and closing HTML tag with a blank line.

<div class="alert is-critical"> **Always** follow every opening and closing HTML tag with _a blank line_. </div>
      
      <div class="alert is-critical">

  **Always** follow every opening and closing HTML tag with _a blank line_.

</div>
    

慣常但不要求 結束 HTML標記之前新增一個空白行。

It is customary but not required to precede the closing HTML tag with a blank line as well.

標題

Title

每份指南都必須有標題。

Every guide document must have a title.

標題應該出現在物理頁面的頂部。使用 markdown # character 開始標題。或者,也可以編寫等效的 <h1>

The title should appear at the top of the physical page. Begin the title with the markdown # character. Alternatively, you can write the equivalent <h1>.

# Angular documentation style guide
      
      # Angular documentation style guide
    

每篇文件只有一個標題( <h1> )!

Only one title (<h1>) per document!

標題文字應該出現在“句子大小寫”中,這意味著第一個單詞是大寫的,所有其它單詞都是小寫的(除非它們是總是大寫的技術術語,比如“Angular”)。

Title text should be in "Sentence case", which means the first word is capitalized and all other words are lower case (unless they are technical terms that are always capitalized, like "Angular").

# Deprecation policy in Angular
      
      # Deprecation policy in Angular
    

始終使用至少一個空行來跟隨標題。

Always follow the title with at least one blank line.

注意,相應的 left-nav TOC 文字應該是“titlecase”,這意味著你可以使用大寫字母來開始第一個單詞和所有主要單詞。對於第二個單詞,例如“in”,“of”和“the”,請使用小寫字母。也可以縮短 TOC 標題以適應該列。

Note that the corresponding left-nav TOC text should be in "title case", which means that you use capital letters to start the first words and all principal words. Use lower case letters for secondary words such as "in", "of", and "the". The TOC title can also be shortened to fit in the column.

部分

Sections

典型文件分為幾個部分。

A typical document is divided into sections.

所有標題文字都應該出現在“Sentence case”中,這意味著第一個單詞是大寫的,所有其它的單詞都是小寫的。

All heading text should be in "Sentence case", which means the first word is capitalized and all other words are lower case.

務必遵循帶有至少一個空白行的標題部分。

Always follow the section heading with at least one blank line.

Main section heading

There are usually one or more main sections that may be further divided into secondary sections.

使用 markdown 的 ## 字元開始一個主要部分標題。或者,你可以編寫等效的 <h2> HTML 標記。

Begin a main section heading with the markdown ## characters. Alternatively, you can write the equivalent <h2> HTML tag.

主要部分的標題後面應該是一個空行,然後是該標題的內容。

The main section heading should be followed by a blank line and then the content for that heading.

## Sections A typical document is divided into sections.
      
      ## Sections

A typical document is divided into sections.
    

Secondary section heading

第二節標題與一個主標題相關,並該標題的範圍內文字形式出現

A secondary section heading is related to a main heading and falls textually within the bounds of that main heading.

使用 markdown ### 字元開始第二個標題。或者,你可以編寫等效的 <h3> HTML 標記。

Begin a secondary heading with the markdown ### characters. Alternatively, you can write the equivalent <h3> HTML tag.

第二個標題之後應該是一個空行,然後是該標題的內容。

The secondary heading should be followed by a blank line and then the content for that heading.

### Secondary section heading A secondary section ...
      
      ### Secondary section heading

A secondary section ...
    

附加章節標題

Additional section headings

儘量減少航向深度,最好只用兩個。但是,如果有更多的標題,比如這個標題,如果有意義,就是允許的。

Try to minimize the heading depth, preferably only two. But more headings, such as this one, are permitted if they make sense.

注意目錄產生器只考慮 main( <h2> )和 secondary( <h3> )標題。

N.B.: The Table-of-contents generator only considers main (<h2>) and secondary (<h3>) headings.

#### Additional section headings Try to minimize ...
      
      #### Additional section headings

Try to minimize ...
    

目錄

Table of contents

大多數頁面都會顯示一個目錄(TOC)。當畫面很寬時,TOC 會出現在右側面板中。當它變窄時,TOC 會出現在靠近頁面頂部的可擴充套件/可摺疊區域。

Most pages display a table of contents (TOC). The TOC appears in the right panel when the viewport is wide. When narrow, the TOC appears in an expandable/collapsible region near the top of the page.

你不應該手工建立自己的 TOC。TOC 是從頁面的 main 和 secondary section 頭自動產生的。

You should not create your own TOC by hand. The TOC is generated automatically from the page's main and secondary section headers.

要從 TOC 中排除標題,就要在標題為“no-toc”的 <h2><h3> 元素中建立標題。markdown 你不能這麼做。

To exclude a heading from the TOC, create the heading as an <h2> or <h3> element with a class called 'no-toc'. You can't do this with markdown.

<h3 class="no-toc"> This heading is not displayed in the TOC </h3>
      
      <h3 class="no-toc">
This heading is not displayed in the TOC
</h3>
    

你可以用標籤 <h1> 標籤和 no-toc 類別來關閉整個頁面的 TOC 產生。

You can turn off TOC generation for the entire page by writing the title with an <h1> tag and the no-toc class.

<h1 class="no-toc"> A guide without a TOC </h1>
      
      <h1 class="no-toc">
A guide without a TOC
</h1>
    

螢幕頂部,左側和底部的導航連結是從 JSON 配置檔案的 contents content/navigation.json

The navigation links at the top, left, and bottom of the screen are generated from the JSON configuration file, content/navigation.json.

修改 navigation.json 檔案的許可權僅限於少數核心團隊成員。但是對於一個新的指南頁面,你應該在左側導航面板中推薦一個名為“side nav”的導航標題和位置。

The authority to change the navigation.json file is limited to a few core team members. But for a new guide page, you should suggest a navigation title and position in the left-side navigation panel called the "side nav".

navigation.json 查詢 SideNav 節點。SideNav 節點是一個導航節點陣列。每個節點都是單個文件的專案節點,或者是帶有子節點的節點。

Look for the SideNav node in navigation.json. The SideNav node is an array of navigation nodes. Each node is either an item node for a single document or a header node with child nodes.

找到你頁面的標題。例如,一個描述 Angular 特性的指南頁面可能是 Fundamentals 頭的子代。

Find the header for your page. For example, a guide page that describes an Angular feature is probably a child of the Fundamentals header.

{ "title": "Fundamentals", "tooltip": "The fundamentals of Angular", "children": [ ... ] }
      
      {
  "title": "Fundamentals",
  "tooltip": "The fundamentals of Angular",
  "children": [ ... ]
}
    

節點子節點可以是一個專案節點,也可以是另一個節點。如果你的指南頁屬於子標題,請在 JSON 中找到該子標題。

A header node child can be an item node or another header node. If your guide page belongs under a sub-header, find that sub-header in the JSON.

為指南新增一個item節點,作為相應節點的子節點。它可能看起來像這樣。

Add an item node for your guide page as a child of the appropriate header node. It probably looks something like this one.

{ "url": "guide/architecture", "title": "Architecture", "tooltip": "The basic building blocks of Angular applications." }
      
      {
  "url": "guide/architecture",
  "title": "Architecture",
  "tooltip": "The basic building blocks of Angular applications."
}
    

導航節點具有以下屬性:

A navigation node has the following properties:

  • url - 指南頁面的 URL( 僅限 item 節點 )。

    url- the URL of the guide page (item node only).

  • title - 側邊導航欄中顯示的文字。

    title- the text displayed in the side nav.

  • tooltip - 讀者將滑鼠懸停在導航連結上方時顯示的文字。

    tooltip - text that appears when the reader hovers over the navigation link.

  • children - 子節點陣列( 僅限標頭節點 )。

    children - an array of child nodes (header node only).

  • hidden - 如果這是一個應該在導航面板中顯示的指南頁面,就定義並設定為 true。很少需要,它是一種隱藏頁面導航的方法,同時讓那些應該知道它的讀者可以訪問它。這個 “作者風格指南”是一個隱藏的頁面。

    hidden - defined and set true if this is a guide page that should not be displayed in the navigation panel. Rarely needed, it is a way to hide the page from navigation while making it available to readers who should know about it. This "Authors Style Guide" is a hidden page.

不要建立既是頭部又是專案節點的節點。也就是說,不要指定節點的 url 屬性。

Do not create a node that is both a header and an item node. That is, do not specify the url property of a header node.

當前的指南允許三級導航結構,它有兩個標題級別。不要新增第三個標題級別。

The current guidelines allow for a three-level navigation structure with two header levels. Don't add a third header level.

程式碼片段

Code snippets

本指南中包含很多 Angular 程式碼的工作範例。範例程式碼可以是終端視窗中輸入的命令,TypeScript 或 HTML 的片段,也可以是整個程式碼檔案。

Guides are rich in examples of working Angular code. Example code can be commands entered in a terminal window, a fragment of TypeScript or HTML, or an entire code file.

無論是什麼原始碼,doc Viewer 都會把它們渲染為“程式碼片段”,既可以單獨使用程式碼範例元件,也可以作為帶選項元件的標籤式集合。

Whatever the source, the doc viewer renders them as "code snippets", either individually with the code-example component or as a tabbed collection with the code-tabs component.

程式碼範例

Code example

你可以用一個簡單的內聯程式碼片段(markdown backtick syntax)來顯示它。當參考程式碼或句子中的檔名時,就在術語的兩邊使用一個反引號。一些例子如下:

You can display a simple, inline code snippet with the markdown backtick syntax. Use a single backtick on either side of a term when referring to code or the name of a file in a sentence. The following are some examples:

  • app.component.ts,新增一個 logger() 方法。

    In the app.component.ts, add a logger() method.

  • 這個 name 屬性是 Sally

    The name property is Sally.

  • 將元件類別名稱新增到 declarations 陣列中。

    Add the component class name to the declarations array.

降價促銷如下:

The markdown is as follows:

* In the `app.component.ts`, add a `logger()` method. * The <code class="no-auto-link">item</code> property is `true`. * Add the component class name to the `declarations` array.
      
      * In the `app.component.ts`, add a `logger()` method.
* The <code class="no-auto-link">item</code> property is `true`.
* Add the component class name to the `declarations` array.
    

在某些情況下,當你在一個術語周圍應用反引號時,它可以自動連結到 API 文件。如果你不打算把這個詞當成連結,請使用以下語法:

In certain cases, when you apply backticks around a term, it may auto-link to the API documentation. If you do not intend the term to be a link, use the following syntax:

The <code class="no-auto-link">item</code> property is `true`.
      
      The <code class="no-auto-link">item</code> property is `true`.
    

對於塊程式碼片段,我們通常更喜歡使用 Angular 文件中的程式碼範例元件( <code-example> 標籤)來表示程式碼。<code-example> 標籤有一個 header 屬性,用於標識該例子所來自的檔案。應該儘可能使用頭來建立這個例子的上下文。欲知詳情,請參閱程式碼段和程式碼範例

For block code snippets, we generally prefer to display code with the Angular documentation code-example component represented by the <code-example> tag. The <code-example> tag has a header attribute that you use to identify the file that the example comes from. The header should be used whenever possible to establish the context of the example. See Code snippets and code examples for more details.

Inline code-snippets

你應儘可能程式碼片段中獲取原始碼片段。但有時內聯程式碼片段是更好的選擇。

You should source code snippets from working sample code when possible. But there are times when an inline snippet is the better choice.

對於終端輸入和輸出,把內容放在 <code-example> 標籤之間,把 CSS 類別設定為 code-shell,並把該屬性設定為 sh 如本例所示。

For terminal input and output, put the content between <code-example> tags, set the CSS class to code-shell, and set the language attribute to sh as in this example.

npm start
      
      npm start
    
<code-example language="sh" class="code-shell"> npm start </code-example>
      
      <code-example language="sh" class="code-shell">
  npm start
</code-example>
    

這裡的內聯手寫程式碼片段是不可測試的,因此本質上是不可靠的。這個例子屬於一小組預先批准的內聯片段,它們包括命令 shell 中的使用者輸入或者某個程序的輸出

Inline, hand-coded snippets like this one are not testable and, therefore, are intrinsically unreliable. This example belongs to the small set of pre-approved, inline snippets that includes user input in a command shell or the output of some process.

不要寫內聯程式碼片段,除非你有充分的理由和編輯的許可。在所有其它情況下,應該從經過測試的程式碼範例中自動產生程式碼片段。

Do not write inline code snippets unless you have a good reason and the editor's permission to do so. In all other cases, code snippets should be generated automatically from tested code samples.

對於假設的例子,例如 JSON 檔案中配置選項的插圖,你仍然應該使用帶有 header 屬性的 <code-example> 標籤來標識上下文。

For hypothetical examples such as illustrations of configuration options in a JSON file, you should still use The <code-example> tag with the header attribute to identify the context.

Code snippets and code samples

文件設計目標之一是,指南頁面程式碼片段應該是實際工作程式碼的例子。

One of the documentation design goals is that guide page code snippets should be examples of real, working code.

我們透過直接從獨立程式碼範例派生的程式碼片段(專為這些指南頁面編寫)來實現這一目標。

We meet this goal by displaying code snippets that are derived directly from standalone code samples, written specifically for these guide pages.

指南頁面的作者負責支援該頁面的程式碼範例。作者還必須為該樣本編寫端到端的測試。

The author of a guide page is responsible for the code sample that supports that page. The author must also write end-to-end tests for the sample.

程式碼範例位於 angular/angular 儲存函式庫的 angular/angular content/examples 目錄的子資料夾中。範例資料夾名稱應該與它支援的指南頁面相同。

Code samples are located in sub-folders of the content/examples directory of the angular/angular repository. An example folder name should be the same as the guide page it supports.

指南頁面可能沒有自己的範例程式碼。它可能代之以屬於另一個頁面的樣本。

A guide page might not have its own sample code. It might refer instead to a sample belonging to another page.

Angular CI 流程會為每個 Angular PR 執行所有的端到端測試。Angular 在每個新版本的樣本和 Angular 本身的每一個新版本之後重新測試樣本。

The Angular CI process runs all end-to-end tests for every Angular PR. Angular re-tests the samples after every new version of a sample and every new version of Angular itself.

如果可能,指南頁上的每一段程式碼都應該從程式碼範例檔案中派生出來。你可以透過配置 <code-example> 屬性來告訴 Angular 文件引擎哪些程式碼檔案(或程式碼檔案的片段)。

When possible, every snippet of code on a guide page should be derived from a code sample file. You tell the Angular documentation engine which code file - or fragment of a code file - to display by configuring <code-example> attributes.

檔案來自一個檔案的程式碼片斷

Code snippet from a file

這個 “Authors Doc Style Guide”有自己的範例應用,它位於 content/examples/docs-style-guide 資料夾中。

This "Authors Doc Style Guide" has its own sample application, located in the content/examples/docs-style-guide folder.

下列程式碼範例展示了該範例的 app.module.ts

The following code-example displays the sample's app.module.ts.

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
src/app/app.module.ts
      
      import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
    

這裡是製作冗長程式碼片段的簡短標記:

Here's the brief markup that produced that lengthy snippet:

<code-example path="docs-style-guide/src/app/app.module.ts" header="src/app/app.module.ts"> </code-example>
      
      <code-example
  path="docs-style-guide/src/app/app.module.ts"
  header="src/app/app.module.ts">
</code-example>
    

你透過在“ content/examplespath 屬性設定為 sample 資料夾的位置,來識別出該程式碼片段的原始檔。在這個例子中,該路徑是 docs-style-guide/src/app/app.module.ts

You identified the snippet's source file by setting the path attribute to sample folder's location within content/examples. In this example, that path is docs-style-guide/src/app/app.module.ts.

你添加了一個標題來透過設定 header 屬性告訴讀者在哪裡找到該檔案。按照慣例,你會把 header 屬性設定為該檔案的根資料夾下的該檔案所在的位置。

You added a header to tell the reader where to find the file by setting the header attribute. Following convention, you set the header attribute to the file's location within the sample's root folder.

除非另有說明,否則本頁面中的所有程式碼片段均來自位於的 content/examples/docs-style-guide 目錄下的範例原始碼。

Unless otherwise noted, all code snippets in this page are derived from sample source code located in the content/examples/docs-style-guide directory.

如果路徑中標識的檔案不存在或是git -ignored,那麼 doc 工具會報錯

The doc tooling reports an error if the file identified in the path does not exist or is git-ignored.

大多數 .js 檔案都是git -ignored。如果你想在專案中包含一個被忽略的程式碼檔案並把它顯示在指南中,你必須取消它。

Most .js files are git-ignored. If you want to include an ignored code file in your project and display it in a guide you must un-ignore it.

取消忽略某個檔案的首選方法是像這樣更新一下 content/examples/.gitignore

The preferred way to un-ignore a file is to update the content/examples/.gitignore like this:

# my-guide !my-guide/src/something.js !my-guide/more-javascript*.js
content/examples/.gitignore
      
      # my-guide
!my-guide/src/something.js
!my-guide/more-javascript*.js
    

程式碼範例屬性

Code-example attributes

你透過設定一個或多個屬性來控制程式碼範例輸出:

You control the code-example output by setting one or more of its attributes:

  • path - content/examples 資料夾中該檔案的路徑。

    path- the path to the file in the content/examples folder.

  • header - 程式碼清單的標題。

    header- the header of the code listing.

  • region - 顯示帶有該地區名的原始檔 fragment; 域名由原始檔中的docregion標記標識,如下所述

    region- displays the source file fragment with that region name; regions are identified by docregion markup in the source file, as explained below.

  • linenums - 值可能是 truefalse 或者是 number。未指定時,行號預設為 false (即不顯示行號)。很少使用的 number 選項會在給定的值下開始行編號。linenums=4,起始行號為 4。

    linenums- value may be true, false, or a number. When not specified, line numbers default to false (i.e. no line numbers are displayed). The rarely used number option starts line numbering at the given value. linenums=4 sets the starting line number to 4.

  • class - code snippets 可以用 CSS 類別的 no-boxcode-shellavoid 來設定風格。

    class- code snippets can be styled with the CSS classes no-box, code-shell, and avoid.

  • hideCopy - 隱藏複製按鈕

    hideCopy- hides the copy button

  • language - 原始碼語言,比如 javascripthtmlcsstypescriptjsonsh。該屬性僅適用於內聯範例。

    language- the source code language such as javascript, html, css, typescript, json, or sh. This attribute only works for inline examples.

顯示程式碼片段

Displaying a code fragment

你可能希望專注於範例程式碼檔案中的程式碼片段。在這個例子中,你將專注於 AppModule 類別及其 NgModule 元資料。

Often you want to focus on a fragment of code within a sample code file. In this example, you focus on the AppModule class and its NgModule metadata.

@NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
      
      @NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
    

首先,你使用命名的docregion在原始檔中包圍該片段,如下所述。然後,就像這樣,在 <code-example>region 屬性中參考那個docregion

First you surround that fragment in the source file with a named docregion as described below. Then you reference that docregion in the region attribute of the <code-example> like this

<code-example path="docs-style-guide/src/app/app.module.ts" region="class"> </code-example>
      
      <code-example
  path="docs-style-guide/src/app/app.module.ts"
  region="class">
</code-example>
    

幾點意見:

A couple of observations:

  1. region"class" 是原始檔中 #docregion 的名字。透過檢視 content/examples/docs-style-guide/src/app/app.module.ts

    The region value, "class", is the name of the #docregion in the source file. Confirm that by looking at content/examples/docs-style-guide/src/app/app.module.ts

  2. 當片段的來源很明顯時,省略 header 是很好的。我們剛剛說過,這是 app.module.ts 檔案的一個片段,裡面是完整的,上面帶有一個標題。沒有必要重複這個標題。

    Omitting the header is fine when the source of the fragment is obvious. We just said that this is a fragment of the app.module.ts file which was displayed immediately above, in full, with a header. There's no need to repeat the header.

壞程式碼的例子

Example of bad code

有時,你想要顯示一個壞程式碼或糟糕設計的例子。

Sometimes you want to display an example of bad code or bad design.

你應該小心點讀者並不總是仔細閱讀過,並且可能會把壞程式碼的例子複製並貼上到自己的應用中。所以,不要經常出現錯誤的程式碼。

You should be careful. Readers don't always read carefully and are likely to copy and paste your example of bad code in their own applications. So don't display bad code often.

執行此操作時,請將 class 設定為 avoid。該程式碼片段將以鮮紅色框起,以引起讀者的注意。

When you do, set the class to avoid. The code snippet will be framed in bright red to grab the reader's attention.

這裡是Angular Style 指南中 “avoid”範例的標記。

Here's the markup for an "avoid" example in the Angular Style Guide.

<code-example path="styleguide/src/05-03/app/heroes/shared/hero-button/hero-button.component.avoid.ts" region="example" header="app/heroes/hero-button/hero-button.component.ts"> </code-example>
      
      <code-example
  path="styleguide/src/05-03/app/heroes/shared/hero-button/hero-button.component.avoid.ts"
  region="example"
  header="app/heroes/hero-button/hero-button.component.ts">
</code-example>
    
/* avoid */ @Component({ selector: '[tohHeroButton]', templateUrl: './hero-button.component.html' }) export class HeroButtonComponent {}
app/heroes/hero-button/hero-button.component.ts
      
      /* avoid */

@Component({
  selector: '[tohHeroButton]',
  templateUrl: './hero-button.component.html'
})
export class HeroButtonComponent {}
    

程式碼標籤

Code Tabs

程式碼選項卡會像程式碼範例那樣顯示程式碼。額外的好處是,它們可以在選項卡式介面中顯示多個程式碼範例。使用程式碼窗格顯示每個標籤頁。

Code tabs display code much like code examples do. The added advantage is that they can display multiple code samples within a tabbed interface. Each tab is displayed using code pane.

Code-tabs 屬性

Code-tabs attributes

  • linenums :值可以是 truefalse,也可以是表示起始行號的數字。如果沒有指定,預設為 false

    linenums: The value can be true, false or a number indicating the starting line number. If not specified, it defaults to false.

程式碼窗格屬性

Code-pane attributes

  • path - content / examples 資料夾中的一個檔案

    path - a file in the content/examples folder

  • header - 在標籤的標題中看到

    header - seen in the header of a tab

  • linenums (覆蓋 linenums - 覆蓋此特定窗格的 code-tabs 級別的 linenums 屬性。值可以是 truefalse,也可以是表示起始行號的數字。如果沒有指定,預設為 false

    linenums - overrides the linenums property at the code-tabs level for this particular pane. The value can be true, false or a number indicating the starting line number. If not specified, it defaults to false.

下一個例子顯示了多個程式碼標籤,每個標籤都有自己的標頭。它展示了對 <code-tabs><code-pane> 級別的行號顯示的控制。

The next example displays multiple code tabs, each with its own header. It demonstrates control over display of line numbers at both the <code-tabs> and <code-pane> levels.

<h1>{{title}}</h1> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{selectedHero.name}} details!</h2> <div><label>id: </label>{{selectedHero.id}}</div> <div> <label>name: </label> <input [(ngModel)]="selectedHero.name" placeholder="name"/> </div> </div>import { Component } from '@angular/core'; import { Hero, HEROES } from './hero'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Authors Style Guide Sample'; heroes = HEROES; selectedHero: Hero; onSelect(hero: Hero): void { this.selectedHero = hero; } }.heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; }{ "scripts": { "start": "concurrently \"npm run build:watch\" \"npm run serve\"", "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", "lint": "tslint ./src/**/*.ts -t verbose" } }
      
      
  1. <h1>{{title}}</h1>
  2. <h2>My Heroes</h2>
  3. <ul class="heroes">
  4. <li *ngFor="let hero of heroes"
  5. [class.selected]="hero === selectedHero"
  6. (click)="onSelect(hero)">
  7. <span class="badge">{{hero.id}}</span> {{hero.name}}
  8. </li>
  9. </ul>
  10. <div *ngIf="selectedHero">
  11. <h2>{{selectedHero.name}} details!</h2>
  12. <div><label>id: </label>{{selectedHero.id}}</div>
  13. <div>
  14. <label>name: </label>
  15. <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  16. </div>
  17. </div>

這是該例子的標記。

Here's the markup for that example.

注意 <code-tabs>linenums 屬性如何顯式啟用所有窗格的編號。第二個窗格中的 linenums 屬性自己禁用了行號。

Note how the linenums attribute in the <code-tabs> explicitly enables numbering for all panes. The linenums attribute in the second pane disables line numbering for itself only.

<code-tabs linenums="true"> <code-pane header="app.component.html" path="docs-style-guide/src/app/app.component.html"> </code-pane> <code-pane header="app.component.ts" path="docs-style-guide/src/app/app.component.ts" linenums="false"> </code-pane> <code-pane header="app.component.css (heroes)" path="docs-style-guide/src/app/app.component.css" region="heroes"> </code-pane> <code-pane header="package.json (scripts)" path="docs-style-guide/package.1.json"> </code-pane> </code-tabs>
      
      <code-tabs linenums="true">
  <code-pane
    header="app.component.html"
    path="docs-style-guide/src/app/app.component.html">
  </code-pane>
  <code-pane
    header="app.component.ts"
    path="docs-style-guide/src/app/app.component.ts"
    linenums="false">
  </code-pane>
  <code-pane
    header="app.component.css (heroes)"
    path="docs-style-guide/src/app/app.component.css"
    region="heroes">
  </code-pane>
  <code-pane
    header="package.json (scripts)"
    path="docs-style-guide/package.1.json">
  </code-pane>
</code-tabs>
    

原始碼標記

Source code markup

<code-example><code-tabs> 元件顯示之前,你必須先為原始碼檔案範例新增特殊的程式碼片段標記。

You must add special code snippet markup to sample source code files before they can be displayed by <code-example> and <code-tabs> components.

該頁面的範例原始碼位於 context/examples/docs-style-guide,其中包含本節中描述的每個程式碼片段標記的範例。

The sample source code for this page, located in context/examples/docs-style-guide, contains examples of every code snippet markup described in this section.

程式碼片段標記總是採用註釋的形式。這是 TypeScript 或 JavaScript 檔案的預設docregion標記:

Code snippet markup is always in the form of a comment. Here's the default docregion markup for a TypeScript or JavaScript file:

// #docregion ... some code ... // #enddocregion
      
      // #docregion
... some code ...
// #enddocregion
    

不同的檔案型別有不同的註釋語法,所以要相應調整

Different file types have different comment syntax so adjust accordingly.

<!-- #docregion --> ... some HTML ... <!-- #enddocregion -->
      
      <!-- #docregion -->
... some HTML ...
<!-- #enddocregion -->
    
/* #docregion */ ... some CSS ... /* #enddocregion */
      
      /* #docregion */
... some CSS ...
/* #enddocregion */
    

文件產生過程會先刪除這些註釋,然後才能在 doc 檢視器中顯示它們。它還會從 stackblitz 和範例程式碼下載中刪除它們。

The doc generation process erases these comments before displaying them in the doc viewer. It also strips them from stackblitz and sample code downloads.

JSON 檔案中不支援程式碼片斷標記,因為 JSON 檔案中的註釋是被禁止的。關於詳情和解決方法,請參閱下文

Code snippet markup is not supported in JSON files because comments are forbidden in JSON files. See below for details and workarounds.

#docregion

#docregion是最重要的一段程式碼段標記。

The #docregion is the most important kind of code snippet markup.

<code-example><code-tabs> 元件除非有#docregion,否則不會顯示原始碼檔案。

The <code-example> and <code-tabs> components won't display a source code file unless it has a #docregion.

#docregion 的註釋開始於程式碼片段區域。該註釋後面的每一行程式碼都屬於該區域,直到程式碼片段處理器遇到該檔案的末尾或者結束#enddocregion 為止

The #docregion comment begins a code snippet region. Every line of code after that comment belongs in the region until the code fragment processor encounters the end of the file or a closing #enddocregion.

src/main.ts 是一個檔案頂部帶有#docregion的檔案的簡單例子。

The src/main.ts is a simple example of a file with a single #docregion at the top of the file.

import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule);
src/main.ts
      
      import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);
    

命名的 #docregions

Named #docregions

你經常會在同一個檔案中的不同片段中顯示多個片段。你可以透過賦予每個片段自己的#docregion 名稱來區分它們,如下所示。

You'll often display multiple snippets from different fragments within the same file. You distinguish among them by giving each fragment its own #docregion name as follows.

// #docregion region-name ... some code ... // #enddocregion region-name
      
      // #docregion region-name
... some code ...
// #enddocregion region-name
    

記得在 <code-example><code-pane>region 屬性中按名稱參考這個區域,就像上面的例子一樣:

Remember to refer to this region by name in the region attribute of the <code-example> or <code-pane> as you did in an example above like this:

<code-example path="docs-style-guide/src/app/app.module.ts" region="class"></code-example>
      
      <code-example
  path="docs-style-guide/src/app/app.module.ts"
  region="class"></code-example>
    

沒有名字的#docregion預設的區域不要設定 region 指的是預設#docregion時屬性。

The #docregion with no name is the default region. Do not set the region attribute when referring to the default #docregion.

巢狀的#docregions

Nested #docregions

#docregions內可以巢狀#docregions

You can nest #docregions within #docregions

// #docregion ... some code ... // #docregion inner-region ... more code ... // #enddocregion inner-region ... yet more code ... /// #enddocregion
      
      // #docregion
... some code ...
// #docregion inner-region
... more code ...
// #enddocregion inner-region
... yet more code ...
/// #enddocregion
    

src/app/app.module.ts 檔案中有一個巢狀區域的好例子。

The src/app/app.module.ts file has a good example of a nested region.

結合片段

Combining fragments

你可以透過定義多個具有相同區域名稱的 #docregions,把一個檔案中的多個片段組合到一個程式碼片段中。

You can combine several fragments from the same file into a single code snippet by defining multiple #docregions with the same region name.

檢查那個定義了兩個巢狀#docregionssrc/app/app.component.ts 檔案。

Examine the src/app/app.component.ts file which defines two nested #docregions.

內部的 class-skeleton 區域出現了兩次,一次捕獲開啟類別定義的程式碼,一次捕獲關閉類別定義的程式碼。

The inner, class-skeleton region appears twice, once to capture the code that opens the class definition and once to capture the code that closes the class definition.

// #docplaster ... // #docregion class, class-skeleton export class AppComponent { // #enddocregion class-skeleton title = 'Authors Style Guide Sample'; heroes = HEROES; selectedHero: Hero; onSelect(hero: Hero): void { this.selectedHero = hero; } // #docregion class-skeleton } // #enddocregion class, class-skeleton
      
      // #docplaster
...
// #docregion class, class-skeleton
export class AppComponent {
// #enddocregion class-skeleton
  title = 'Authors Style Guide Sample';
  heroes = HEROES;
  selectedHero: Hero;

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
// #docregion class-skeleton
}
// #enddocregion class, class-skeleton
    

onSelect(hero:Hero):void {this.selectedHero = hero; } // #docregion class-skeleton} // #enddocregion class,class-skeleton

這裡是並排顯示的兩個相應的程式碼片段。

Here's are the two corresponding code snippets displayed side-by-side.

export class AppComponent { title = 'Authors Style Guide Sample'; heroes = HEROES; selectedHero: Hero; onSelect(hero: Hero): void { this.selectedHero = hero; } }export class AppComponent { }
      
      export class AppComponent {
  title = 'Authors Style Guide Sample';
  heroes = HEROES;
  selectedHero: Hero;

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}
    

一些意見:

Some observations:

  • 頂部的 #docplaster 是另一段程式碼片段標記。它告訴處理器如何把片段連成一個片段。

    The #docplaster at the top is another bit of code snippet markup. It tells the processor how to join the fragments into a single snippet.

    在這個例子中,我們告訴處理器把碎片放在一起,兩者之間沒有任何東西 - 沒有任何“石膏”。大多數樣本檔案定義了這個空白膏藥

    In this example, we tell the processor to put the fragments together without anything in between - without any "plaster". Most sample files define this empty plaster.

    如果我們忽略新增 #docplaster,處理器就會在片段之間插入一個預設的 plaster #docplaster 省略號註釋)。嘗試自己刪除 #docplaster 評論以檢視效果。

    If we neglected to add, #docplaster, the processor would insert the default plaster - an ellipsis comment - between the fragments. Try removing the #docplaster comment yourself to see the effect.

  • #docregion 一個註釋提到了兩個區域的名字,#enddocregion 註釋也是如此。這是在同一程式碼行中啟動(或停止)多個區域的便捷方式。你可以把這些註釋放在不同的行上,很多作者都喜歡這樣做。

    One #docregion comment mentions two region names as does an #enddocregion comment. This is a convenient way to start (or stop) multiple regions on the same code line. You could have put these comments on separate lines and many authors prefer to do so.

JSON 檔案

JSON files

JSON 檔案不支援程式碼片斷標記,因為 JSON 檔案中的註釋是被禁止的。

Code snippet markup is not supported for JSON files because comments are forbidden in JSON files.

你可以在 src 屬性中參考它來顯示一個完整的 JSON 檔案。但你無法顯示 JSON 片段,因為你無法在檔案中新增 #docregion 標籤。

You can display an entire JSON file by referring to it in the src attribute. But you can't display JSON fragments because you can't add #docregion tags to the file.

如果 JSON 檔案太大,你可以將感興趣的節點複製到 markdown 反引號中。

If the JSON file is too big, you could copy the nodes-of-interest into markdown backticks.

不幸的是,用這種方式錯誤地建立無效的 JSON 很容易。首選的方法是使用要顯示的片段建立一個 JSON 部分檔案。

Unfortunately, it's easy to mistakenly create invalid JSON that way. The preferred way is to create a JSON partial file with the fragment you want to display.

你無法測試這個區域性檔案,也決不會在應用中使用它。但至少你的 IDE 可以確認它在語法上是正確的。

You can't test this partial file and you'll never use it in the application. But at least your IDE can confirm that it is syntactically correct.

這是一個從 package.json 摘錄到某個名為 package.1.json 的部分檔案的例子。

Here's an example that excerpts certain scripts from package.json into a partial file named package.1.json.

{ "scripts": { "start": "concurrently \"npm run build:watch\" \"npm run serve\"", "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", "lint": "tslint ./src/**/*.ts -t verbose" } }
package.json (selected scripts)
      
      {
  "scripts": {
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "lint": "tslint ./src/**/*.ts -t verbose"
  }
}
    
<code-example path="docs-style-guide/package.1.json" header="package.json (selected scripts)"></code-example>
      
      <code-example
  path="docs-style-guide/package.1.json"
  header="package.json (selected scripts)"></code-example>
    

部分檔案命名

Partial file naming

很多導遊會講故事。在那個故事中,該應用會逐步發展,通常會使用簡單或不完整的程式碼。

Many guides tell a story. In that story, the app evolves incrementally, often with simplistic or incomplete code along the way.

要想在程式碼中講這個故事,你通常需要使用那些沒有出現在最終應用中的程式碼片段來建立最終原始碼檔案的部分檔案或中間版本。

To tell that story in code, you'll often need to create partial files or intermediate versions of the final source code file with fragments of code that don't appear in the final app.

這些區域性檔案和中間檔案都需要自己的名字。按照 doc 範例命名約定進行操作。在副檔名前加一個數字,如下圖所示:

Such partial and intermediate files need their own names. Follow the doc sample naming convention. Add a number before the file extension as illustrated here:

package.1.json app.component.1.ts app.component.2.ts
      
      package.1.json
app.component.1.ts
app.component.2.ts
    

在 Angular 的文件中,你可以在樣本中找到很多這樣的檔案。

You'll find many such files among the samples in the Angular documentation.

記得把它們寫在 stackblitz.json,從 stackblitz 中排除這些檔案,如下所示。

Remember to exclude these files from stackblitz by listing them in the stackblitz.json as illustrated here.

{ "description": "Authors style guide", "files": [ "!**/*.d.ts", "!**/*.js", "!**/*.[1,2,3].*" ], "tags": ["author", "style guide"] }
stackblitz.json
      
      {
  "description": "Authors style guide",
  "files": [
    "!**/*.d.ts",
    "!**/*.js",
    "!**/*.[1,2,3].*"
  ],
  "tags": ["author", "style guide"]
}
    

實例

Live examples

透過在頁面中新增 <live-example>,你可以產生在 Stackblitz 即時編碼環境中執行範例程式碼的連結,並把它下載到讀者的檔案系統中。

By adding <live-example> to the page you generate links that run sample code in the Stackblitz live coding environment and download that code to the reader's file system.

實例(AKA“stackblitz”)由程式碼範例資料夾根目錄下的一個或多個 stackblitz.json 檔案定義。每個範例資料夾通常都有一個無名的定義檔案,預設是 stackblitz.json

Live examples (AKA "stackblitz") are defined by one or more stackblitz.json files in the root of a code sample folder. Each sample folder usually has a single unnamed definition file, the default stackblitz.json.

你可以透過 name.stackblitz.json 格式建立其它的命名定義檔案。參閱 content/examples/testing 中的例子。

You can create additional, named definition files in the form name.stackblitz.json. See content/examples/testing for examples.

stackblitz.json 的架構還沒有被記錄下來,但檢視範例資料夾中的 stackblitz.json 檔案可以告訴你大部分需要知道的事情。

The schema for a stackblitz.json hasn't been documented yet but looking at the stackblitz.json files in the example folders should tell you most of what you need to know.

在頁面中新增 <live-example></live-example> 可以產生兩個預設連結。

Adding <live-example></live-example> to the page generates the two default links.

現場演練 / 下載範例

  1. 指向 stackblitz 的連結,該堆疊是由預設的 stackblitz.json 檔案定義的,該檔案位於程式碼範例資料夾目錄下,其名稱與該引導頁面同名。

    a link to the Stackblitz defined by the default stackblitz.json file located in the code sample folder with the same name as the guide page.

  2. 下載該範例的連結

    a link that downloads that sample.

單擊第一個連結可以在新的瀏覽器選項卡中開啟 StackBlitz 上的程式碼範例。

Clicking the first link opens the code sample on StackBlitz in a new browser tab.

你可以用屬性和類別來改變實例的外觀和行為。

You can change the appearance and behavior of the live example with attributes and classes.

Custom label and tooltip

透過設定 title 屬性,給 live 引數錨定一個自訂標籤和工具提示。

Give the live example anchor a custom label and tooltip by setting the title attribute.

Live Example with title / 下載範例

<live-example title="Live Example with title"></live-example>
      
      <live-example title="Live Example with title"></live-example>
    

你可以把標籤放在 <live-example> 標籤之間來達到同樣的效果:

You can achieve the same effect by putting the label between the <live-example> tags:

包含內容標籤的實例

Live example with content labelLive example with content label / 下載範例

<live-example>Live example with content label</live-example>
      
      <live-example>Live example with content label</live-example>
    

Live example from another guide

要連結到名字與當前指南頁不同的資料夾中的 Stackblitz,請把 name 屬性設定為該資料夾的名字。

To link to a Stackblitz in a folder whose name is not the same as the current guide page, set the name attribute to the name of that folder.

“路由器指南”中的“實例”

Live Example from the Router guideLive Example from the Router guide / 下載範例

<live-example name="router">Live Example from the Router guide</live-example>
      
      <live-example name="router">Live Example from the Router guide</live-example>
    

Live Example for named Stackblitz

要連結到一個名叫 stackblitz.json 檔案,請設定 stackblitz 屬性。下面的例子連結到當前指南目錄下的 second.stackblitz.json 定義的 second.stackblitz.json

To link to a Stackblitz defined by a named stackblitz.json file, set the stackblitz attribute. The following example links to the Stackblitz defined by second.stackblitz.json in the current guide's directory.

現場演練 / 下載範例

<live-example stackblitz="second"></live-example>
      
      <live-example stackblitz="second"></live-example>
    

Live Example without download

要跳過這個下載連結,noDownload 新增 noDownload 屬性。

To skip the download link, add the noDownload attribute.

就是 Stackblitz

Just the StackblitzJust the Stackblitz

<live-example noDownload>Just the Stackblitz</live-example>
      
      <live-example noDownload>Just the Stackblitz</live-example>
    

Live Example with download-only

要跳過 Stackblitz 的即時連結,只能連結到下載地址,你可以新增 downloadOnly 屬性。

To skip the live Stackblitz link and only link to the download, add the downloadOnly attribute.

只下載

Download onlyDownload only

<live-example downloadOnly>Download only</live-example>
      
      <live-example downloadOnly>Download only</live-example>
    

Embedded live example

預設情況下,實例連結會在單獨的瀏覽器選項卡中開啟 Stackblitz。你可以透過 embedded 屬性在指南頁面中嵌入 Stackblitz。

By default, a live example link opens a Stackblitz in a separate browser tab. You can embed the Stackblitz within the guide page itself by adding the embedded attribute.

出於效能原因,Stackblitz 並沒有馬上啟動。讀者會看到一幅影象。單擊該圖片可以啟動在頁面上的 iframe 中啟動嵌入式 Stackblitz 的慢速啟動過程。

For performance reasons, the Stackblitz does not start right away. The reader sees an image instead. Clicking the image starts the sometimes-slow process of launching the embedded Stackblitz within an iframe on the page.

這裡是本指南的嵌入式實例。

Here's an embedded live example for this guide.

<live-example embedded></live-example>
      
      <live-example embedded></live-example>
    

你還可以 下載這個例子

錨點

Anchors

每個 section header 標籤都是一個錨點。另一個指南頁面可以寫一下這個部分的連結:

Every section header tag is also an anchor point. Another guide page could add a link to this section by writing:

欲知詳情,請參閱“錨點”部分。

See the "Anchors" section for details.

<div class="alert is-helpful"> See the ["Anchors"](guide/docs-style-guide#anchors "Style Guide - Anchors") section for details. </div>
      
      <div class="alert is-helpful">

See the ["Anchors"](guide/docs-style-guide#anchors "Style Guide - Anchors") section for details.

</div>
    

在頁面中導航時,你可以在指定滾動到本節開頭的連結時省略頁面的 URL。

When navigating within the page, you can omit the page URL when specifying the link that scrolls up to the beginning of this section.

... the link that [scrolls up](#anchors "Anchors") to ...
      
      ... the link that [scrolls up](#anchors "Anchors") to ...
    

醜陋的長節頭錨

Ugly, long section header anchors

鎖定一個好的錨名通常是個好主意。

It is often a good idea to lock-in a good anchor name.

這段 section header 文字有時會產生一個不具吸引力的錨點。這個非常糟糕。

Sometimes the section header text makes for an unattractive anchor. This one is pretty bad.

[This one](#ugly-long-section-header-anchors) is pretty bad.
      
      [This one](#ugly-long-section-header-anchors) is pretty bad.
    

更大的危險是,標題文字未來的重寫會破壞本章的連結。

The greater danger is that a future rewording of the header text would break a link to this section.

出於這些原因,明智的做法是使用特殊的 語法,明確地新增一個自訂錨點,就在它所應用的標題或文字的上方。

For these reasons, it is often wise to add a custom anchor explicitly, just above the heading or text to which it applies, using the special syntax like this.

#### Ugly, long section header anchors #### 醜陋的長節頭錨
      
      

#### Ugly, long section header anchors

#### 醜陋的長節頭錨
    

現在就像之前那樣連結到那個自訂錨名稱

Now link to that custom anchor name as you did before.

Now [link to that custom anchor name](#ugly-anchors) as you did before.
      
      Now [link to that custom anchor name](#ugly-anchors) as you did before.
    

或者,你也可以使用 HTML <a> 標籤。

Alternatively, you can use the HTML <a> tag.

如果你這樣做,一定要設定 id 屬性 - 而不是 name 屬性! docs 產生器不會把這個 name 轉換成正確的連結 URL。

If you do, be sure to set the id attribute - not the name attribute! The docs generator will not convert the name to the proper link URL.

<a id="anchors"></a> ## Anchors
      
      <a id="anchors"></a>

## Anchors
    

警報和 Calllouts

Alerts and Callouts

警報和標註會顯示警告,額外的細節或對其它頁面的參考。它們還可以用來提供評論,豐富讀者對正在渲染的內容的理解。

Alerts and callouts present warnings, extra detail or references to other pages. They can also be used to provide commentary that enriches the reader's understanding of the content being presented.

警告或標註不得含有對理解至關重要的資訊。不要把一個重要的指令或一個指導步驟放進一個小節中。

An alert or callout must not contain anything essential to that understanding. Don't put a critical instruction or a tutorial step in a subsection.

提醒

Alerts

提示會引起人們的注意。警報不應該用於多行內容(改為使用標註 )。

Alerts draw attention to short important points. Alerts should not be used for multi-line content (use callouts instead).

你還會從下面章節中瞭解實例的風格。

You'll learn about styles for live examples in the section below.

請注意,開始和結束的 <div> 標記都必須至少有一個空白行。在結束 </div> 之前的一個空白行是慣用的但不是必需的。

Note that at least one blank line must follow both the opening and closing <div> tags. A blank line before the closing </div> is customary but not required.

<div class="alert is-helpful"> You'll learn about styles for live examples in the [section below](guide/docs-style-guide#live-examples "Live examples"). </div>
      
      <div class="alert is-helpful">

You'll learn about styles for live examples in the [section below](guide/docs-style-guide#live-examples "Live examples").

</div>
    

根據內容的嚴重程度或重要性,有三種不同的緊急程度用來對警報進行風格設定。

There are three different urgency levels used to style the alerts based on the severity or importance of the content.

一個關鍵的警報

A critical alert.

一個重要的警示。

An important alert.

一個有用的資訊警報。

A helpful, informational alert.

這是這些警報的標記。

Here is the markup for these alerts.

<div class="alert is-critical"> A critical alert. </div> <div class="alert is-important"> An important alert. </div> <div class="alert is-helpful"> A helpful, informational alert. </div>
      
      <div class="alert is-critical">

A critical alert.

</div>

<div class="alert is-important">

An important alert.

</div>

<div class="alert is-helpful">

A helpful, informational alert.

</div>
    

標註

Callouts

標註(比如警報)就是為了引起人們對重點的注意。如果你想要一個鉚接頭和多行內容,請使用 callout。

Callouts, like alerts, are meant to draw attention to important points. Use a callout when you want a riveting header and multi-line content.

如果你有兩個以上的段落,考慮建立一個新的頁面,或者讓它成為主要內容的一部分。

If you have more than two paragraphs, consider creating a new page or making it part of the main content.

標註使用與警報相同的緊急程度

Callouts use the same urgency levels that alerts do.

A critical point

乾草叉連帽衫符文系列,屋頂派對彈出古代信使斜挎包信譽卡爾斯蓬亂的特呂弗年代。符號學:符拉西奇(Viroredweven)的“符號學”(Semiotics viral freegan VHS)。Intelligentsia 羽衣甘藍籌碼副四美元吐司

Pitchfork hoodie semiotics, roof party pop-up paleo messenger messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast

An important point

乾草叉連帽衫符文系列,屋頂派對彈出式古代信使包信得卡爾斯凌亂的特呂弗。符號學:符拉西奇(Viroredweven)的“符號學”(Semiotics viral freegan VHS)。Intelligentsia 羽衣甘藍籌碼副四美元吐司

Pitchfork hoodie semiotics, roof party pop-up paleo messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast

A helpful or informational point

乾草叉連帽衫符文系列,屋頂派對彈出式古代信使包信得卡爾斯凌亂的特呂弗。符號學:符拉西奇(Viroredweven)的“符號學”(Semiotics viral freegan VHS)。Intelligentsia 羽衣甘藍籌碼副四美元吐司

Pitchfork hoodie semiotics, roof party pop-up paleo messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast

這是第一個標註中的標記。

Here is the markup for the first of these callouts.

<div class="callout is-critical"> <header>A critical point</header> **Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast </div>
      
      <div class="callout is-critical">
<header>A critical point</header>

**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast

</div>
    

注意:

Notice that:

  • callout 標題文字強制全部用大寫形式寫成

    the callout header text is forced to all upper case

  • 標註體可以用 markdown 來書寫

    the callout body can be written in markdown

  • 一個空白行用來區分 </header> 標記和 markdown 內容

    a blank line separates the </header> tag from the markdown content

標註旨在引起使用者的注意。他們不是偶然的旁白。請謹慎使用它們。

Callouts are meant to grab the user's attention. They are not for casual asides. Please use them sparingly.

樹木

Trees

樹可以表示分層資料。

Trees can represent hierarchical data.

sample-dir
src
app
app.component.ts
app.module.ts
styles.css
tsconfig.json
node_modules ...
package.json

這是這個檔案樹的標記。

Here is the markup for this file tree.

<div class='filetree'> <div class='file'> sample-dir </div> <div class='children'> <div class='file'> src </div> <div class='children'> <div class='file'> app </div> <div class='children'> <div class='file'> app.component.ts </div> <div class='file'> app.module.ts </div> </div> <div class='file'> styles.css </div> <div class='file'> tsconfig.json </div> </div> <div class='file'> node_modules ... </div> <div class='file'> package.json </div> </div> </div>
      
      <div class='filetree'>
    <div class='file'>
        sample-dir
    </div>
    <div class='children'>
        <div class='file'>
          src
        </div>
        <div class='children'>
            <div class='file'>
              app
            </div>
            <div class='children'>
                <div class='file'>
                  app.component.ts
                </div>
                <div class='file'>
                  app.module.ts
                </div>
            </div>
            <div class='file'>
              styles.css
            </div>
            <div class='file'>
              tsconfig.json
            </div>
        </div>
        <div class='file'>
          node_modules ...
        </div>
        <div class='file'>
          package.json
        </div>
    </div>
</div>
    

表格

Tables

使用 HTML 表來表達表格式資料。

Use HTML tables to present tabular data.

FrameworkTaskSpeed
AngularJSRoutingFast
Angular v2Routing

Faster

Angular v4Routing

Fastest :)

這是這個表的標記。

Here is the markup for this table.

<style> td, th {vertical-align: top} </style> <table> <tr> <th>Framework</th> <th>Task</th> <th>Speed</th> </tr> <tr> <td><code>AngularJS</code></td> <td>Routing</td> <td>Fast</td> </tr> <tr> <td><code>Angular v2</code></td> <td>Routing</td> <!-- can use markdown too; remember blank lines --> <td> *Faster* </td> </tr> <tr> <td><code>Angular v4</code></td> <td>Routing</td> <td> **Fastest :)** </td> </tr> </table>
      
      <style>
  td, th {vertical-align: top}
</style>

<table>
  <tr>
    <th>Framework</th>
    <th>Task</th>
    <th>Speed</th>
  </tr>
  <tr>
    <td><code>AngularJS</code></td>
    <td>Routing</td>
    <td>Fast</td>
  </tr>
  <tr>
    <td><code>Angular v2</code></td>
    <td>Routing</td>
    <!-- can use markdown too; remember blank lines -->
    <td>

      *Faster*

    </td>
  </tr>
  <tr>
    <td><code>Angular v4</code></td>
    <td>Routing</td>
    <td>

      **Fastest :)**

    </td>
  </tr>
</table>
    

圖片

Images

Image location

將 images content/images 目錄中的 content/images 在與該指南頁面具有相同 URL 的資料夾中。這個“作者風格指南”頁面的 content/images/guide/docs-style-guide 屬於 content/images/guide/docs-style-guide 資料夾。

Store images in the content/images directory in a folder with the same URL as the guide page. Images for this "Authors Style Guide" page belong in the content/images/guide/docs-style-guide folder.

Angular doc generation 會把這些影象資料夾拷貝到runtime generated/images執行時位置。將 image src 屬性設定為該目錄下的開始。

Angular doc generation copies these image folders to the runtime location, generated/images. Set the image src attribute to begin in that directory.

這是屬於這個頁面的“飛行英雄”影象的 src 屬性。

Here's the src attribute for the "flying hero" image belonging to this page.

src="generated/images/guide/docs-style-guide/flying-hero.png"
      
      src="generated/images/guide/docs-style-guide/flying-hero.png"
    

Use the HTML <img> tag

不要使用降價影象語法![...](...)。

Do not use the markdown image syntax, ![...](...).

影象應該在 <img> 標籤中指定。

Images should be specified in an <img> tag.

為了便於訪問,我們總是用一個有意義的圖片描述來設定 alt 屬性。

For accessibility, always set the alt attribute with a meaningful description of the image.

你應該把 <img> 標籤巢狀在一個 <div class="lightbox"> 標籤中,該標籤用來為陰影框內的影象設定風格。你需要編輯的跳過許可 lightbox 於它的類別 div 封裝。

You should nest the <img> tag within a <div class="lightbox"> tag, which styles the image within a drop-shadow frame. You'll need the editor's permission to skip the lightbox class on its div encapsulation.

這是一個很有道理的例子

Here's a conforming example

<div class="lightbox"> <img src="generated/images/guide/docs-style-guide/flying-hero.png" alt="flying hero"> </div>
      
      <div class="lightbox">
  <img src="generated/images/guide/docs-style-guide/flying-hero.png"
    alt="flying hero">
</div>
    

請注意,HTML 圖片元素沒有結束標記。

Note that the HTML image element does not have a closing tag.

Image dimensions

doc 產生器從檔案中讀取影象尺寸,並自動為 img 標籤新增 width 和 height 屬性。如果要控制影象的大小,請提供自己的 width 和 height 屬性。

The doc generator reads the image dimensions from the file and adds width and height attributes to the img tag automatically. If you want to control the size of the image, supply your own width and height attributes.

這裡是“飛行英雄”,規模更合理。

Here's the "flying hero" at a more reasonable scale.

<div class="lightbox"> <img src="generated/images/guide/docs-style-guide/flying-hero.png" alt="flying Angular hero" width="200"> </div>
      
      <div class="lightbox">
  <img src="generated/images/guide/docs-style-guide/flying-hero.png"
    alt="flying Angular hero"
    width="200">
</div>
    

寬視訊可能是個問題。大多數瀏覽器嘗試對影象進行重新縮放,但是在某些畫面中,寬影象可能會溢位文件。

Wide images can be a problem. Most browsers try to rescale the image but wide images may overflow the document in certain viewports.

不要設定大於 700px 的寬度。如果你想顯示一個更大的影象,提供一個指向實際影象的連結,使用者可以點選它來分別檢視全尺寸影象,就像“Ahead-of-time 編譯”中 source-map-explorer 輸出的例子一樣。指南:

Do not set a width greater than 700px. If you wish to display a larger image, provide a link to the actual image that the user can click on to see the full size image separately as in this example of source-map-explorer output from the "Ahead-of-time Compilation" guide:

Image compression

大影象檔案載入速度慢,損害了使用者體驗。始終壓縮影象。考慮使用圖片壓縮網站,比如tinypng

Large image files can be slow to load, harming the user experience. Always compress the image. Consider using an image compression web site such as tinypng.

Floating images

你可以透過分別應用 class =“left”或 class =“right”來把圖片浮動到文字的左側或右側。

You can float the image to the left or right of text by applying the class="left" or class="right" attributes respectively.

飛 Angular 英雄

flying Angular hero

這段文字環繞著浮動的“飛行英雄”形象的右側。

This text wraps around to the right of the floating "flying hero" image.

標題和程式碼範例會自動清除浮動畫像。如果你需要強制一段文字來清除漂浮的圖片,你可以新增 <br class="clear"> 文字中斷的地方。

Headings and code-examples automatically clear a floating image. If you need to force a piece of text to clear a floating image, add <br class="clear"> where the text should break.


上例中的標記是:

The markup for the above example is:

<img src="generated/images/guide/docs-style-guide/flying-hero.png" alt="flying Angular hero" width="200" class="left"> This text wraps around to the right of the floating "flying hero" image. Headings and code-examples automatically clear a floating image. If you need to force a piece of text to clear a floating image, add `<br class="clear">` where the text should break. <br class="clear">
      
      <img src="generated/images/guide/docs-style-guide/flying-hero.png"
   alt="flying Angular hero"
   width="200"
   class="left">

This text wraps around to the right of the floating "flying hero" image.

Headings and code-examples automatically clear a floating image. If you need to force a piece of text to clear a floating image, add `<br class="clear">` where the text should break.

<br class="clear">
    

請注意,通常不會在 <figure> 元素中包裝浮動畫像。

Note that you generally don't wrap a floating image in a <figure> element.

漂浮在一個小節裡面

Floating within a subsection

如果在 alert,callout 或子 section 中都有浮動畫像,最好把 clear-fix 類別應用到 div 以確保該影象不會溢位其容器。例如:

If you have a floating image inside an alert, callout, or a subsection, it is a good idea to apply the clear-fix class to the div to ensure that the image doesn't overflow its container. For example:

飛 Angular 英雄

flying Angular hero

帶有markdown格式文字的子分區

A subsection with markdown formatted text.

<div class="alert is-helpful clear-fix"> <img src="generated/images/guide/docs-style-guide/flying-hero.png" alt="flying Angular hero" width="100" class="right"> A subsection with **markdown** formatted text. </div>
      
      <div class="alert is-helpful clear-fix">

  <img src="generated/images/guide/docs-style-guide/flying-hero.png"
    alt="flying Angular hero"
    width="100"
    class="right">

  A subsection with **markdown** formatted text.

</div>