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. day33——进程的创建方式、pid、空间隔离、join方法、其他属性、守护进程

    day33 进程创建的两种方式 在windows环境下,开启进程必须在______name______ == "______main______"下面 p.start(): 只是向 ...

  2. TextField 、 FTE、 TLF 的使用情景和简单说明

    作者:tiangej 来源:CSDN 原文:https://blog.csdn.net/tiangej/article/details/16859239 版权声明:本文为博主原创文章,转载请附上博文链 ...

  3. Gym 102055B Balance of the Force

    大意: $n$个骑士, 第$i$个骑士若加入光明阵营, 那么能力值$L_i$, 加入黑暗阵营, 能力值$D_i$. 给定$m$个限制$(u_i,v_i)$, 表示$u_i,v_i$不能在同一阵营. 求 ...

  4. win7远程服务器发生身份验证错误,要求的函数不受支持

    远程服务器发生身份验证错误,要求的函数不受支持,远程登录服务器以前都是正常的,今天登录远程桌面就一直是这样的错误.记录一下解决方法. 方法一:卸载补丁KB41037181.打开控制面板,找到“程序和功 ...

  5. 论文笔记 XGBoost: A Scalable Tree Boosting System

    XGBoost是boosting算法的其中一种.Boosting算法的思想是将许多弱分类器集成在一起形成一个强分类器,其更关注与降低基模型的偏差.XGBoost是一种提升树模型(Gradient bo ...

  6. CarbonCopyCloner 硬盘对拷

    CarbonCopyCloner 硬盘对拷 建议使用 5.1.14-b1以上的版本. 安装文件包 CarbonCopyCloner-5.1.14-b1.dmg ================== E ...

  7. Libev库学习

    Libev库学习 https://www.cnblogs.com/wunaozai/p/3950249.html Libev库学习(1)https://www.cnblogs.com/wunaozai ...

  8. 【转载】 C#使用string.IsNullOrWhiteSpace方法判断字符串是否为非空字符

    在C#编程过程中,很多时候需要判断传入过来的字符串是否为Null或者空字符或者空白字符,此时就可以使用到string.IsNullOrWhiteSpace方法来判断,如果字符串为null或者空字符Em ...

  9. php生成一维码以及保存-转载

    地址:http://www.cnblogs.com/ForEvErNoME/archive/2012/04/21/2460944.html 注释掉: //header('Content-Type: i ...

  10. 织梦dedecms是什么?

    织梦dedecms是什么?DedeCms是织梦内容管理系统(DedeCms)的简称, 以简单.实用.开源而闻名,是国内最知名的PHP开源网站管理系统,也是使用用户最多的PHP类CMS系统; DedeC ...