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. 嵌入式02 STM32 实验02 端口输入输出各4种模式

    GPIO(General-purpose input/output 通用目的输入/输出端口) 电压(A模拟量)与电平(D数字量) GPIO 8种工作模式(输入四种.输出四种) 1.GPIO_Mode_ ...

  2. Redis-缓存有效期与淘汰策略

    Redis-缓存有效期与淘汰策略 有效期 节省空间 做到数据弱一致性,有效期失效后,可以保证数据的一致性 过期策略 Redis过期策略通常有三种: 1.定时过期: 每个设置过期时间的Key,系统还要生 ...

  3. PAT(B) 1055 集体照(Java)

    题目链接:1055 集体照 (25 point(s)) 题目描述 拍集体照时队形很重要,这里对给定的 N 个人 K 排的队形设计排队规则如下: 每排人数为 N/K(向下取整),多出来的人全部站在最后一 ...

  4. Modelsim——do脚本、bat命令

    一.do脚本实现自动化仿真 Modelsim是支持命令的,我们可以用 .do 文件将这些命令先写好然后在Modelsim上调用.因为我的编辑器不支持.do的语法,所以这里改用 .tcl文件,它和 .d ...

  5. HuTool之判断上传文件的文件类型

    文件类型判断-FileTypeUtil 由来 在文件上传时,有时候我们需要判断文件类型.但是又不能简单的通过扩展名来判断(防止恶意脚本等通过上传到服务器上),于是我们需要在服务端通过读取文件的首部几个 ...

  6. 解决跟Docker私有仓库登陆,推送,拉取镜像出现的报错

    出现问题:Error response from daemon: Get https://192.168.186.120/v1/users/: dial tcp 192.168.186.120:443 ...

  7. Dubbo学习摘录(二)

    扩展点机制 扩展点的配置 (1)根据关键字读取配置,获取具体的实现类 比如在 dubbo-demo-provider.xml 文件中配置: 则会根据rmi去读取具体的协议实现类RmiProtocol. ...

  8. JDK提供的原子类和AbstractQueuedSynchronizer(AQS)

    大致分成: 1.原子更新基本类型 2.原子更新数组 3.原子更新抽象类型 4.原子更新字段 import java.util.concurrent.atomic.AtomicInteger; impo ...

  9. lombok使用教程

    Lombok介绍.使用方法和总结https://www.cnblogs.com/heyonggang/p/8638374.html Lombok简介.使用.工作原理.优缺点https://www.ji ...

  10. MVC-08模型

    部分7:添加数据模型. MVC模型 MVC模型包含所有应用程序逻辑(业务逻辑.验证逻辑.数据访问逻辑),除了纯视图和控制器逻辑. 通过MVC,模型可保存并操作应用程序数据. Models文件夹 Mod ...