angular项目创建
1.安装node
2.通过npm安装angular的脚手架 npm install -g @angular/cli
3.安装之后输入ng v如果出现angular红色文字的话则说明安装成功
4.通过脚手架创建angular项目 ng new angularDemo
5.运行项目 ng serve
项目文件目录
在app文件夹下有app.module.ts是根模块,app.component.html,app.component.scss和app.component.ts是根组件
app.module.ts
// angular核心模块
import { NgModule } from '@angular/core';
// 引入浏览器解析模块
import { BrowserModule } from '@angular/platform-browser';
// 根组件
import { AppComponent } from './app.component';
// @NgModule装饰器,接受一个元数据对象,告诉angular如何编译和启动对象
@NgModule({
declarations: [ //配置当前项目运行的组件
AppComponent
],
imports: [ //配置当前模块运行依赖的其他模块
BrowserModule
],
providers: [], //配置项目所需的服务
bootstrap: [AppComponent] //指定应用主试图(称为根组件),通过引导根组件appModule来启动应用,这里一般写的是根组件
})
// 根模块不需要导出任何东西,因为其他模块不需要导入根模块
export class AppModule { }
app.component.ts
// 引入核心模块里的Component
import { Component } from '@angular/core';
// 一个装饰器
@Component({
selector: 'app-root', //使用这个组件名称
templateUrl: './app.component.html', //html
styleUrls: ['./app.component.less'] //css
})
export class AppComponent {
title = 'angulardemo01'; //定义属性
}
创建组件
angular是一个组件化,模块化的开发,你可以创建一个组件然后在另一个组件中去使用
在angular里面我们可以通过一个命令就实现组件的创建
ng g //来查看我们要创建的内容选项
ng g component Components /news //选择创建组件,并且指定创建文件目录
当你要使用自己创建的组件的话需要在app.module.tsl里面引入这个组件,并且配置在declarations里面。但是如果你通过指令创建的话就会自动引入并且配置了。然后把news组件通过名字的方式放在你想用的位置就可以使用这个组件了,比如
<app-news></app-news>
//我在app.component.html使用了news组件,
//这个组件的名字在news.component.ts的selector属性去查看
我们通常定义数据的话,在xxx.component.ts里面定义就ok 不需要通过var来声明。 比如: news.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
title = '我是一个news组件 --ts'
constructor() { }
ngOnInit(): void {
}
}
然后我们在组件里面通过{{}}来引用定义的数据
news.component.html
<h1>{{title}}</h1>