初始化
快速搭建一个angular项目:
- npm install -g @angular/cli安装脚手架
- ng new angular-web 创建项目
- cd angular-web 切换到项目
- ng serve 启动项目
文件目录结构
创建一个组件component
在终端中输入以下命令:
ng g component views/home
随后在app.component.html中引入组件即可:
<app-home></app-home>
单向双向绑定、原样输出、点击事件
html代码:
原样输出title:{{title}}
<br>
<input type="text" [value]='title'>
<br>
<input type="text" [(ngModel)]="title">
<br>
<button (click)="alertTitle()">点击弹出title</button>
ts代码:
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
public title: string = '这是一个标题';
constructor() {
}
ngOnInit(): void {
}
alertTitle(){
alert(this.title);
}
}
angular的双向绑定是需要引入FormsModule模块:
父子组件的相互传值
home父组件:
html代码块:
<app-header #header [home]='this' [successFun]='success'></app-header>
<hr>
这是home内容
<button (click)="setHeader()">通过按钮传递参数改变子组件标题</button>
ts代码块:
import { Component, OnInit , ViewChild} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
@ViewChild('header') header: any;
constructor() {
}
ngOnInit(): void {
}
ngAfterViewInit():void{
console.log(this.header)
}
setHeader(){
this.header._initData("父子组改变了标题")
}
success(){
alert("这是父组正在执行刷新操作")
}
}
header子组件:
html代码块:
<p>{{title}}</p>
<button (click)="success()">子组件调用父组件中的刷新方法</button>
ts代码块:
import { Component, OnInit ,Input } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.sass']
})
export class HeaderComponent implements OnInit {
public title:string = '这是头部的标题'
@Input() home:any;
@Input() successFun:any;
constructor() { }
ngOnInit(): void {
}
_initData(title:string = ''){
this.title = title;
}
success(){
this.successFun()
}
}
创建服务封装请求
为了避免每个页面请求都import HttpClient模块,所以对其进行了封装。
在终端中输入以下命令:
ng g service service/common
common.service.ts文件代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CommonService {
public baseURL: string = 'http:xxxxx';
constructor(public http: HttpClient) { }
get(api) {
return new Promise((resolver, reject) => {
this.http.get(this.baseURL + api).subscribe((response) => {
resolver(response)
})
})
}
}
使用服务中封装的get进行请求
import { Component, OnInit , ViewChild} from '@angular/core';
import { CommonService } from '../../service/common.service'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
constructor(public common:CommonService) {
}
ngOnInit(): void {
var api = 'api/xxxx'
this.common.get(api).then((response)=>{
//这里将返回请求结果
console.log(response);
})
}
}
以上就是我对Angular的一点使用,如果文章由于我学识浅薄,导致您发现有严重谬误的地方,请一定在评论中指出,我会在第一时间修正我的文章,以避免误人子弟。