安装扩展

Angular Snippets (Version 8)
google 扩展
angury


一、如何新建一个组件

ng g component components/xxx 名字

1.项目结构

  1. 项目结构
  2. app.module.ts //根模块
  3. @NgModule({
  4. // 注册组件
  5. declarations: [
  6. AppComponent,
  7. HeaderComponent
  8. ],
  9. imports: [
  10. BrowserModule
  11. ],
  12. providers: [],
  13. bootstrap: [AppComponent]
  14. })
  15. export class AppModule { }

2.组件插入

  1. //app.component.html
  2. <app-header></app-header>
  3. <app-content></app-content>

二、渲染及属性绑定

  1. public arr:object [] = [{name:"html",age:10},{name:"css",age:30}]
  2. public isShow:boolean = true;
  3. public imageUrl:string="http://5b0988e595225.cdn.sohucs.com/images/20180726/84bd17514858436d930736d0d73af0c7.jpeg"
  4. public msg:string = "我喜欢写代码"

if for 渲染

  1. <div *ngFor="let item of arr">{{item.name}}</div>
  2. <div *ngIf="isShow">你好</div>
  3. <img [src]="imageUrl" alt="">
  4. <p (click)="handleClick()">{{msg}}</p>

1.双向数据绑定

1.1 app.module.ts中配置

  1. import {FormsModule} from '@angular/forms'
  2. ...
  3. imports: [
  4. BrowserModule,
  5. FormsModule
  6. ],

例子1 input框value值绑定

  1. //heard.components.html
  2. <input type="text" [(ngModel)]="msg">
  1. //headr.components.ts
  2. public msg:string="这是一个head"

image.png


例子2 check框checked值绑定

  1. <input type="checkbox" [(ngModel)]="checked"
  2. (ngModelChange)="handleCheck()"
  3. >

三、事件

1.click

  1. <p (click)="handleClick()">{{msg}}</p>
  1. public checked:boolean=true;
  2. handleCheck(){
  3. console.log(this.checked)
  4. }
  1. export class HeaderComponent implements OnInit {
  2. ....
  3. public msg:string ="我喜欢写代码"
  4. constructor() { }
  5. ngOnInit() {
  6. }
  7. handleClick(){
  8. this.msg = "change"
  9. }
  10. }

2.keyup

  1. <input type="text" (keyup)="handleEnter($event)">
  1. handleEnter(event:any){
  2. console.log(event.keyCode)
  3. }

2.1keyup.enter

  1. handleEnter(value:string){
  2. console.log(value)
  3. }

3.ngModelChange

获取输入框值

  1. //heard...html
  2. <input type="text" [(ngModel)]="msg"
  3. (ngModelChange)="handleChange($event)"
  4. >
  1. handleChange(e){
  2. console.log(e)
  3. }

四、读取对象的属性

  1. public data:any={
  2. name:"yuan",
  3. age:12
  4. }
  5. //读取
  6. data['name']