Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

angular2 #31

Open
Wscats opened this issue Dec 16, 2016 · 0 comments
Open

angular2 #31

Wscats opened this issue Dec 16, 2016 · 0 comments

Comments

@Wscats
Copy link
Owner

Wscats commented Dec 16, 2016

生成项目并添加组件

安装淘宝镜像

npm install -g cnpm --registry=https://registry.npm.taobao.org

image

安装angular2脚手架

cnpm install -g angular-cli@latest

image

这个命令为我们新建了一个名为hello-angular的工程

ng new hello-angular

image

生成一个hello-angular文件夹,进入文件夹

cd hello-angular

image
可以看到应用编译打包后server运行在4200端口

ng serve

image
打开浏览器输入 http://localhost:4200 即可看到效果

ng generate component wscat--inline-template --inline-style

image

wscat是我们的组件名称,后面的两个参数是告诉angular-cli生成组件时,请把组件的HTML模板和CSS样式和组件放在同一个文件中
Angular提倡的文件命名方式是这样的:

  • 组件名称.component.ts
  • 组件的HTML模板命名为: 组件名称.component.html
  • 组件的样式文件命名为: 组件名称.component.css

image

@component修饰配置中的selector: 'app-login',这意味着我们可以在其他组件的**template**中使用 `

打开hello-angular\src\app\app.component.html加入我们的组件

<h1>
  {{title}}
</h1>
<app-login></app-login>

编写组件添加事件

login.component.ts里面的模板中添加输入框和事件绑定

@Component({
  selector: 'app-login',
  template: `
    <p>
      login Works!
    </p>
    <input />
    <button (click)="test()">Ok</button>
  `,
  styles: []
})

**(click)**表示我们要处理这个button的click事件,圆括号是说发生此事件时,调用等号后面的表达式或函数
在下面代码中定义test事件

export class LoginComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  test(){
		console.log("123")
	}
}

如果一切无误当我们点击按钮的时候就会在控制台输出123结果
image

我们可以在文本输入框标签内加一个#usernameRef,这个叫引用(reference)

<input #usernameRef type="text" />
<button on-click="test(usernameRef.value)">Ok</button>
export class LoginComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  } 
  test(data){
		console.log(data)
	}
}

当我们输入内容的时候再按触发点击事件,就可以获取视图输入框的数据

创建服务

image
在src\app下建立一个core的子文件夹(src\app\core),然后命令行中输入 ng g s core/auth(s这里是service的缩写,core/auth是说在core的目录下建立auth服务相关文件)。auth.service.tsauth.service.spec.ts这个两个文件应该已经出现在你的目录里了

我们可以定义一个简单的服务,如下面代码

import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
  constructor() { }
  loginWithCredentials(username: string, password: string){
    if(username === 'wscats'){
    	return true;
    }else{
    	return false;
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant