二、基本语法

32 阅读1分钟

一、指令

1.结构指令 通过在DOM中添加、移除和替换元素来修改布局

  • *ngFor
<li *ngFor="let item of [1,2,3];let i = index;let odd = odd;trackBy:trackById">{{item}}---{{i}}</li>

  • *ngIf
  <app-detail *ngIf="show"></app-detail>
  • *ngSwitch
  <div [ngSwitch]="conditionExpression">
      <div *ngSwitchCase="expression">output</div>
      <div *ngSwitchDefault>output2</div>
 </div>

2.属性型指令 修改一个现有元素的外观和行为 类似标准的 HTML属性

  • *ngStyle
 <p  [style.font-size.px]="20">test works!</p>
<!-- 对象语法 -->
 <p [ngStyle]="{'color': textColor, 'font-size': fontSize}">
   样式化文本
 </p>

 <!-- 绑定到组件属性 -->
     <p [ngStyle]="styleObject">
   样式化文本
 </p>
  • *ngClass

<!-- 对象语法 -->
<div [ngClass]="{active: isActive, disabled: isDisabled}">
 内容
</div>

<!-- 数组语法 -->
<div [ngClass]="['class1', 'class2']">
 内容
</div>

<!-- 字符串语法 -->
<div [ngClass]="currentClass">
内容
</div>
  • ngModel
 <!-- 基本用法 -->
<input [(ngModel)]="username" placeholder="用户名">

<!-- 分离的 getter/setter -->
<input [ngModel]="username" (ngModelChange)="username = $event">
 

3.自定义

自定义结构性指令

// appUnless.directive.ts
@Directive({
 selector: '[appUnless]'
})
export class UnlessDirective {
 private hasView = false;

 constructor(
   private templateRef: TemplateRef<any>,
   private viewContainer: ViewContainerRef
 ) {}

 @Input() set appUnless(condition: boolean) {
   if (!condition && !this.hasView) {
     this.viewContainer.createEmbeddedView(this.templateRef);
     this.hasView = true;
   } else if (condition && this.hasView) {
     this.viewContainer.clear();
     this.hasView = false;
   }
 }
}

自定义属性指令

// highlight.directive.ts
@Directive({
 selector: '[appHighlight]'
})
export class HighlightDirective {
 @Input() highlightColor = 'yellow';

 constructor(private el: ElementRef) {
   this.el.nativeElement.style.cursor = 'pointer';
 }

 @HostListener('mouseenter') onMouseEnter() {
   this.el.nativeElement.style.backgroundColor = this.highlightColor;
 }

 @HostListener('mouseleave') onMouseLeave() {
   this.el.nativeElement.style.backgroundColor = '';
 }
}

二数据绑定

1. 属性绑定

<img [src]="url" >

2. 事件绑定

<button (click)="onAlert($event)">点击</button>

3.双向绑定


    <input [(ngModel)]="binding"  />
    {{binding}}
  • 注意要在app.module.ts中引入 FormModel
import { FormsModule } from '@angular/forms';
@NgModule({
  declarations: [
  ...
  ],
  imports: [
   ....
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4.模板引用变量(vue/react 中 ref)

方式一

<input type="text" #phone>
<button (click)="show(phone.value)">btn</button>

方式二

<input type="text" ref-phone>
<button (click)="show(phone.value)">btn</button>

5.安全访问符 : ?.