明# 結構型指令 (Structural directives)

說明

  1. 透過新增或移除DOM元素,改變Template頁面佈局(DOM結構)
  2. 主要有ngIf、ngFor、ngSwitch
  3. 星號(*)是Html5新增的<element template=""></element>元素屬性的語法糖,由<template></template>元素演變而來

Template語法:

ngIf
<element *ngIf="條件判斷"></element>
ngFor
<element *ngFor="let variable of iterable;">
  {{variable}}
</element>
ngSwitch
<element [ngSwitch]="變數">
  <child-element-1 *ngSwitchCase="變數值條件1"></child-element-1>
  <child-element-2 *ngSwitchCase="變數值條件2"></child-element-2>
  <child-element-3 *ngSwitchDefault></child-element-3>
</element>

程式碼範例:ngIf

1.在Component.ts中加入方法ckeckNgIf()

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'example-component',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  ckeckNgIf(){
    return 條件判斷(true或false);
  }

  constructor() { }

  ngOnInit() {
  }

}

2.在Template的元素中使用ngIf結構型指令

<h1 *ngIf="ckeckNgIf()">文字</h1>

程式碼範例:ngFor

1.在Component.ts中加入Array: member

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'example-component',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  member = [
    {
      name: "小明",
      sex: "男性"
    },
    {
      name: "小美",
      sex: "女性"
    },
  ]

  constructor() { }

  ngOnInit() {
  }

}

3.在Template的元素中使用ngFor結構型指令

<div *ngFor="let people of member;">
  {{people.name}}的性別是{{people.sex}}
</div>

程式碼範例:ngSwitch

1.在Component.ts中加入變數: mood

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'example-component',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  mood = "普普通通"

  constructor() { }

  ngOnInit() {
  }

}

3.在Template的元素中使用ngSwitch結構型指令

<div [ngSwitch]="mood">
  <p *ngSwitchCase="'美麗'">今天心情很美麗</p>
  <p *ngSwitchCase="'難過'">今天心情不美麗</p>
  <p *ngSwitchDefault>今天心情普普通通</p>
</div>

results matching ""

    No results matching ""