准备工作
安装node js (网络资源下载)
安装cnpm
代码: npm install -g cnpm --registry=https://registry.npm.taobao.org
全局安装angular 脚手架
代码: install -g @angular/cli
验证安装是否完成 ng v
创建项目
ng new DemoName(项目名称)
[该过程中。会通过npm安装一系列的依赖插件,如果没有外网权限,需要等很久,可以关闭掉,直接同过cnpm进行安装 cnpm install ]
运行项目
ng serve --open(打开浏览器)
angular命令行提示工具
https://cli.angular.io/
创建组件
ng g component components/news
引入表单组件(用于数据双向数据绑定)
import {FormsModule} from ‘@angular/forms’
创建服务
步骤一:
ng g service my-services-name(服务名称)
创建至指定目录下
ng g service service/storage (services为目录 storage是服务名称)
步骤二:
//在跟模块中引入服务
import { TestStorageService } from ‘./services/test-storage.service’;
步骤三:
//在跟模块中导入服务
providers: [TestStorageService,],
步骤四:在组件中引入服务
import { TestStorageService } from ‘./services/test-storage.service’
步骤五:在服务中调用方法
constructor(public storage:TestStorageService) {
let s=this.storage.get();
}
viewChild操作dom模型 (父组件操作子组件)
步骤一 模板中给dom命名
<div #myBox>
我是dom节点
</div>
步骤二 业务逻辑中引用
import { Component, OnInit,ViewChild } from '@angular/core';
步骤三 获取dom节点
//获取dom节点
@ViewChild('myBox',{static:true}) myBox:any;
constructor() { }
步骤四 调用 操作dom
ngAfterViewInit():void{
console.log(this.myBox.nativeElement)
this.myBox.nativeElement.style.width='200px';
this.myBox.nativeElement.style.height='100px';
this.myBox.nativeElement.style.background='red';
console.log(this.myBox.nativeElement.innerHTML)
}
步骤四 viewchild操作组件
一:<app-headers #header>
二:@ViewChild(‘header’,{static:true}) header:any;
子组件操作父组件
父组件:
html:
<app-headers [headline]="headline" [msg]="msg" [parentrun]='parentrun'></app-headers>
home.ts:
parentrun(){
alert("父组件的run方法");
}
public msg:string='我是home组件的message';
子组件:
子组件.ts:
//接受父组件传递的数据
@Input() headline:any;
@Input() msg:any;
@Input() parentrun:any;
html:
getParentRun(){
//执行父组件的run方法
this.parentrun();
}
页面直接调用即可:
<h1>{{headline}}</h1>
{{msg}}