进入要新建项目的目录,按住shift+点击鼠标右键打开命令提示符用
输入
ng new angular-hello-world
命令新建angular-hello-world项目
![](https://img.haomeiwen.com/i4342827/5ef1316d8b868c92.png)
用VSCode打开angular-hello-world目录
Ctrl+`
打开VSCode的终端
![](https://img.haomeiwen.com/i4342827/4e2e3f10fb29c98f.png)
在终端中执行
cnpm install
来安装npm依赖包![](https://img.haomeiwen.com/i4342827/be97e845a04e7396.png)
在终端执行
ng serve --open
命令,打开浏览器浏览![](https://img.haomeiwen.com/i4342827/56ca3e461720a027.png)
默认是打开的 4200端口
ng serve也可以指定端口号 如 ng serve --port 8090
项目目录下的src>app目录是源代码的主要编写存放地方,现在新建一个自己的组件component
在VSCode下新建一个终端
![](https://img.haomeiwen.com/i4342827/34fa7754452abb18.png)
输入命令:
ng g component hello-world
![](https://img.haomeiwen.com/i4342827/4e6993b99adaa526.png)
使用命令生成组件的好处是,它会自动在app.module.ts文件中导入这个组件,并在declarations中引入
![](https://img.haomeiwen.com/i4342827/69cd6d92ee7c330a.png)
改写 app.component.html文件 增加组件标签 <app-hello-world></app-hello-world>
![](https://img.haomeiwen.com/i4342827/7d7fba149fd5d3cf.png)
不用刷新浏览器就可以看到 hello-world已经被载入了
新建一个Component user-item ng g component user-item
并在app.component.html中使用这个组件 <app-user-item></app-user-item>
{{name}}表达式绑定和*ngFor指令
user-item.component.ts代码
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user-item',
templateUrl: './user-item.component.html',
styleUrls: ['./user-item.component.css']
})
export class UserItemComponent implements OnInit {
name:string;
names:string[];
constructor() {
this.name="jiangxm";
this.names=['Ari','Peng','jiang','jancy'];
}
ngOnInit() {
}
}
user-item.component.html
<p>
hello {{name}}
</p>
<h2>*ngFor指令</h2>
<ul>
<li *ngFor="let item of names">{{item}}</li>
</ul>
新建 user-list组件 ng g component user-list
并将user-item组件的name属性修改成输入属性
user-item.component.ts中要引入 Input
import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-user-item',
templateUrl: './user-item.component.html',
styleUrls: ['./user-item.component.css']
})
export class UserItemComponent implements OnInit {
@Input() name:string; //输入属性 前面要加上@Input 使用之处用中括号如:[name]="item"
constructor() {
}
ngOnInit() {
}
}
user-item.component.html
<ul>
<li *ngFor="let item of names">
<app-user-item [name]="item"></app-user-item>
</li>
</ul>
网友评论