2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > angular6基本语法 *ngFor *ngIf 获取dom元素 绑定事件

angular6基本语法 *ngFor *ngIf 获取dom元素 绑定事件

时间:2019-08-24 02:53:21

相关推荐

angular6基本语法 *ngFor *ngIf 获取dom元素  绑定事件

文章目录

1.创建组件(1)创建组件(2)使用组件 2.绑定数据(1)插值表达式绑定(2)属性绑定 3.*ngFor4.*ngIf5.*ngSwitch6.获取dom元素7.绑定事件8.双向数据绑定9.管道

1.创建组件

(1)创建组件

//创建一个header组件ng generate component header (简写 ng g c header)//创建自定义服务serviceng generate service header (简写 ng g s header)//创建路由ng generate module app-routing --flat --module=app

(2)使用组件

ponent.html

<app-header></app-header>

2.绑定数据

(1)插值表达式绑定

ponent.html

<h1>{{title}}</h1>

ponent.ts

export class AppComponent {public title: string = 'hello world';}

(2)属性绑定

<!-- 使用[属性]="值"进行属性绑定 --><img [src]="src" /><h1 [ngClass]="{'show': true}">{{title}}</h1><h1 [ngStyle]="{'color': red}">{{title}}</h1><div [id]='id' [title]='title'>绑定属性</div>

3.*ngFor

<ul><li *ngFor="let item of fruits">{{item}}</li></ul>

4.*ngIf

<p *ngIf="fruits.length>2">ngIf判断是否显示</p>

5.*ngSwitch

<span [ngSwitch]="data"><p *ngSwitchCase="1">已付款</p><p *ngSwitchCase="2">待收货</p><p *ngSwitchDefault>完成</p></span>

6.获取dom元素

<div class="msgBox" #msgBox>12333</div><button (click)="submit($event)">确定</button>

import {Component, ElementRef, ViewChild } from '@angular/core'export class AppComponent {@ViewChild('msgBox') msgBox: ElementRefsubmit(e){console.log(this.msgBox.nativeElement)}}

7.绑定事件

<button (click)="onClickEvent($event)">确定</button>

8.双向数据绑定

app.module.ts中引入FormsModule

import {BrowserModule } from '@angular/platform-browser'; //BrowserModule,浏览器的解析模块import {NgModule } from '@angular/core';//angular核心模块import {AppComponent } from './ponent';//根组建import {FormsModule } from '@angular/forms'@NgModule({//装饰器declarations: [//声明组件、指令、管道AppComponent],imports: [ //引入项目需要的模块BrowserModule,FormsModule],providers: [],//声明模块中提供的是什么服务bootstrap: [AppComponent]//声明模块的组件是什么})export class AppModule {} //类

html中使用

<input type="text" [(ngModel)]="title">

9.管道

创建管道

//创建管道ng generate pipe week (简写 ng g p week)

<span>{{item.endTime | week}}</span>

week.pipe.ts

import {Pipe, PipeTransform } from '@angular/core';@Pipe({name: 'week'})export class WeekPipe implements PipeTransform {transform(value: any, args?: any): any {var weekArray = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");return weekArray[new Date(value).getDay()];}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。