美文网首页
angular4-01 app-hello-world

angular4-01 app-hello-world

作者: 漫漫江雪 | 来源:发表于2017-07-19 15:50 被阅读0次

进入要新建项目的目录,按住shift+点击鼠标右键打开命令提示符用
输入

ng new angular-hello-world

命令新建angular-hello-world项目


Paste_Image.png

用VSCode打开angular-hello-world目录

Ctrl+`

打开VSCode的终端

Paste_Image.png
在终端中执行 cnpm install 来安装npm依赖包
Paste_Image.png
在终端执行 ng serve --open 命令,打开浏览器浏览
Paste_Image.png

默认是打开的 4200端口
ng serve也可以指定端口号 如 ng serve --port 8090

项目目录下的src>app目录是源代码的主要编写存放地方,现在新建一个自己的组件component
在VSCode下新建一个终端

Paste_Image.png
输入命令:ng g component hello-world
Paste_Image.png
使用命令生成组件的好处是,它会自动在app.module.ts文件中导入这个组件,并在declarations中引入
Paste_Image.png
改写 app.component.html文件 增加组件标签 <app-hello-world></app-hello-world>
Paste_Image.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>

相关文章

  • angular4-01 app-hello-world

    进入要新建项目的目录,按住shift+点击鼠标右键打开命令提示符用输入 命令新建angular-hello-wor...

网友评论

      本文标题:angular4-01 app-hello-world

      本文链接:https://www.haomeiwen.com/subject/teelkxtx.html