angular-2

作者: 南崽 | 来源:发表于2020-04-29 20:09 被阅读0次

angular基础模板语法

文本绑定

  • {{}}

html绑定

  • [innerHTML]="xxx"

属性绑定

  • [属性]=xxx

class绑定

  • [class]="xxx"
  • [class.active]="布尔值"
  • [ngClass]="{key1:布尔值,key2:布尔值}"

style绑定

  • [style.color]=""
  • [ngStyle]="xxx"

src绑定

  • [src]=""
  • [ng-src]=""

条件渲染

  • *ngIf="条件 else 模板名称"
  • switch

列表渲染

  • *ngFor="let item of list;let i = index"

表单双向绑定

  • 手写
<input [value]="msg" (input)="msg=$event.target.value">
  • 导入模块
    app.module.ts
import {FormsModule} from '@angular/forms';

// 导入表单模块
<input [(ngModel)]="msg">

事件

  • (click)="showMsg($event)"

管道

  • |json
    json管道
  • |date:"YYYY-MM-dd HH:mm:ss"
    日期
  • |number:"1.2-2"
    数字
  • |slice:2-4
    切片

引用

  • <input #myput>
  • myput.value

组件

创建组件

ng g c 文件夹/组件名称
ng g c components/child

  • 在components文件夹创建一个child文件夹
  • .html 模板
    .css CSS
    .ts 组件类
    .spc.ts 测试文件

组件

  • 组件的装饰器
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
  • selector 引用的标签

  • templateUrl 组件的模板

  • styleUrls 组件的css

  • 组件的类

export class ChildComponent implements OnInit {

}
  • implements 实现接口
  • OnInit 组件的生命周期-初始化

组件参数的传递

  • 父传子
 <app-child [list]="list"></app-child>
 @Input() list:string[];
  • 子传父
 @Output() selNum=new EventEmitter();
selNum.emit("数据")
<app-child [list]="list" (selNum)="setType($event)"></app-child>
  • 父获取子 通过ref
<app-child #child2>
{{child2.list}}

childlist数据必须是public

Ref

<p #refp></p>

 import { Component, ViewChild, ElementRef,QueryList,ViewChildren } from '@angular/core';
// 导入组件
@ViewChild("refp",{static:true}) refp:ElementRef;
// 获取操作dom
ngAfterViewInit(){
    this.refp.nativeElement //真正的dom节点 
}
<div *ngFor="#myitem"></div>

@ViewChildren("myitem") myitem:QueryList<ElementRef>;
ngAfterViewInit(){
    this.myitem.forEach(el=>{
      el.nativeElement //真正的节点
    })
  }

服务service

  • 组件间共享的数据和方法提供服务的

创建 ng g s 文件夹/服务名称

ng g s service/search

使用

import {SearchService} from "xxx";
// 导入
constructor (private SearchService:SearchService){}
// 使用
this.SearchService.xxx

相关文章

  • angular-2

    angular基础模板语法 文本绑定 {{}} html绑定 [innerHTML]="xxx" 属性绑定 [属性...

网友评论

      本文标题:angular-2

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