1. Create a src/my-component/files/src/app directory to hold your templates.

mkdir -p src/my-component/files/src/app

2. Create an app.component.ts file in src/my-component/files/src/app and put the following code in it:

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = '<%= name %>';
}

The <%= name %> variable is an option you’ll pass in when running this Schematic. Create an app.component.html file with some HTML that reads the name variable.

3.  Add template as well:

<div style="text-align:center">
<h1>
Hello, {{ name }}
</h1>
</div> <router-outlet></router-outlet>

4. Now what we want is let user to give the 'name' thought prompt, In order to define the name prompt, create a schema.json file in the src/my-component directory.

{
"$schema": "http://json-schema.org/schema",
"id": "SchematicsMyComponent",
"title": "My Component Schema",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Your Name",
"x-prompt": "What is your name?"
}
},
"required": ["name"]
}

Then update src/collection.json to reference this file in a schema property.

{
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"my-component": {
"description": "A blank schematic.",
"factory": "./my-component/index#myComponent",
"schema": "./my-component/schema.json"
}
}
}

5. Then update src/my-component/index.ts so you can get your generated project’s path, and copy templates.

import {
apply,
MergeStrategy,
mergeWith,
move,
Rule,
SchematicContext,
template,
Tree,
url,
FileEnty,
forEach
} from '@angular-devkit/schematics';
import { join, normalize } from 'path';
import { getWorkspace } from '@schematics/angular/utility/config'; export function setupOptions(host: Tree, options: any): Tree {
const workspace = getWorkspace(host);
if (!options.project) {
options.project = Object.keys(workspace.projects)[];
}
const project = workspace.projects[options.project]; options.path = join(normalize(project.root), 'src');
return host;
} export function myComponent(_options: any): Rule {
return (tree: Tree, _context: SchematicContext) => {
setupOptions(tree, _options); const movePath = normalize(_options.path + '/');
const templateSource = apply(url('./files/src'), [
template({..._options}),
move(movePath),
// fix for https://github.com/angular/angular-cli/issues/11337
forEach((fileEntry: FileEntry) => {
if (tree.exists(fileEntry.path)) {
tree.overwrite(fileEntry.path, fileEntry.content);
}
return fileEntry;
}),
]);
const rule = mergeWith(templateSource, MergeStrategy.Overwrite);
return rule(tree, _context);
};
}

We can use this as a template when we want to add some template into the schematics.

6. Test with real application:

ng new my-test-app --routing --style css
cd my-test-app
npm link ../my-component
ng g my-component:my-component

When I tried this, it prompted me:

$ ng g my-component:my-component
? What is your name? Matt
UPDATE src/app/app.component.html ( bytes)
UPDATE src/app/app.component.ts ( bytes)

7. Support for ng add with Angular CLI:

A slick feature of Angular CLI is its ng add command. You can use it to invoke schematics and add features like PWA support and Angular Material to your projects. For example:

ng add @angular/pwa
ng add @angular/material

You can support for ng add $your-schematic too! Open my-component/src/collection.json and add a new ng-add schematic.

{
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"my-component": {
"description": "A blank schematic.",
"factory": "./my-component/index#myComponent",
"schema": "./my-component/schema.json"
},
"ng-add": {
"factory": "./ng-add/index",
"description": "Add schematic",
"schema": "./my-component/schema.json"
}
}
}

Create src/ng-add/index.ts and add the code necessary for it to invoke the my-component schematic.

import { chain, Rule, schematic, SchematicContext, Tree, } from '@angular-devkit/schematics';

export default function (options: any): Rule {
return (host: Tree, context: SchematicContext) => {
return chain([
schematic('my-component', options)
])(host, context);
};
}

After build, link to project, then you can run:

ng add my-component

Source

[Schematics] 1. Copy and Manipulate Template的更多相关文章

  1. 在库中使用schematics——ng add与ng update

    起步 创建一个angular库 ng new demo --create-application=false ng g library my-lib 可见如下目录结构 ├── node_modules ...

  2. vscode c++ cmake template project

    VSCode configure C++ dev environment claim use CMake to build the project. For debugging, VSCode's C ...

  3. DataGridView控件

    DataGridView控件 DataGridView是用于Windows Froms 2.0的新网格控件.它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特 ...

  4. DataGridView控件-[引用]

    DataGridView控件 DataGridView是用于Windows Froms 2.0的新网格控件.它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特 ...

  5. DataGridView控件使用大全说明-各种常用操作与高级操作

    DataGridView控件 DataGridView是用于Windows Froms 2.0的新网格控件.它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特 ...

  6. DataGridView控件使用大全

    转自:http://www.cnblogs.com/xiaofengfeng/archive/2011/04/16/2018504.html DataGridView控件 DataGridView是用 ...

  7. HEC-ResSim原文档

              HEC-ResSim Reservoir System Simulation             User's Manual       Version 3.1 May 201 ...

  8. Apache Spark 1.6 Hadoop 2.6 Mac下单机安装配置

    一. 下载资料 1. JDK 1.6 + 2. Scala 2.10.4 3. Hadoop 2.6.4 4. Spark 1.6 二.预先安装 1. 安装JDK 2. 安装Scala 2.10.4 ...

  9. Sharepoint学习笔记—习题系列--70-576习题解析 -(Q121-Q123)

    Question  121 You are designing a SharePoint 2010 workflow that will be used to monitor invoices. Th ...

随机推荐

  1. Linux学习-IP设置

    网卡命名规则 CENTOS6的网卡命名方式:它会根据情况有所改变而非唯一且固定,在CENTOS6之前,网络接口使用连续号码命名: eth0. eth1等,当增加或删除网卡时,名称可能会发生变化 CEN ...

  2. MapReduce Join关联

    Reduce join 原理 Map端的主要工作:为来自不同表(文件)的key/value对打标签以区别不同来源的记录.然后用连接字段作为key,其余部分和新加的标志作为value,最后进行输出. R ...

  3. 链表习题(8)-寻找单链表中数据域大小为k的结点,并与前一结点交换,如果前一结点存在的情况下

    /*寻找单链表中数据域大小为k的结点,并与前一结点交换,如果前一结点存在的情况下*/ /* 算法思想:定义两个指针,pre指向前驱结点,p指向当前结点,当p->data == k的时候,交换 p ...

  4. python 能做什么(常用库)

    1. 编写脚本,如测试脚本.初始化脚本.运维脚本:pywin32.nose2. 图形界面开发: Tkinter.PyQt . wxPython . PySide .Pillow3. 爬虫: Scrap ...

  5. MySQL运维中的Tips--持续更新

    1.into outfile 生成sql:一般都是生成文本或者其他形式的文件,现在需要生成sql形式的文件.配置文件加secure_file_priv=''select concat('insert ...

  6. 阅读笔记——《How a Facebook rejection pushed me to start and grow a profitable business in 12 months》

    阅读笔记——<How a Facebook rejection pushed me to start and grow a profitable business in 12 months> ...

  7. Exception: HTTP 599: SSL certificate problem: unable to get local issuer certificate 解决办法

    使用Pyspider中报此错误. 错误原因: 这个错误会发生在请求 https 开头的网址,SSL 验证错误,证书有误. 解决方法: 使用self.crawl(url, callback=self.i ...

  8. idea 中激活 JRebel

    JRebel介绍: JRebel是一款JVM插件,它使得Java代码修改后不用重启系统,立即生效.IDEA上原生是不支持热部署的,一般更新了 Java 文件后要手动重启 Tomcat 服务器,修改才能 ...

  9. AD域控服务器更改IP地址步骤

    1.cmd命令行,先停止netlogon服务:net stop netlogon 2.修改本机的IP地址 3.清楚IP缓存:ipconfig /flushdns 4.重启netlogon服务:net ...

  10. Java调用WebService方法总结(3)--wsimport调用WebService

    wsimport是JDK自带的把WSDL转成Java的工具,可以很方便的生成调用WebService的代码.文中所使用到的软件版本:Java 1.8.0_191. 1.准备 参考Java调用WebSe ...