วันพฤหัสบดีที่ 2 มกราคม พ.ศ. 2563

Angular 8 - สร้าง Event กับ Component และ เงื่อนไขในการแสดงผล

หัวข้อที่แล้วเราได้รู้จักกับ *ngFor, Interpolation {{ }} และ Property Binding [ ] ไปแล้ว
ในส่วนที่เราจะมาทำความรู้จักกับอีก 2 ตัวคือ *ngIf และ Event Binding ( ) กัน

พาทนี้ยังอยู่กับ https://angular.io/start ครับ โดยจากภาพแล้วเราจะทำการแสดง Description ออกมา
ส่วน Product ไหนไม่มี Description เราก็จะไม่แสดง

เราจะใช้งาน *ngIf โดยถ้าเงื่อนไขเป็นจริง True ถึงจะแสดง แต่ถ้าไม่เป็นจริง False ก็จะไม่แสดง
กำหนดให้แสดง Description ถ้ามีข้อความ ก็จะเป็น *ngIf="product.description"

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

<div *ngFor="let product of productList">
    <a [title]="'Description: ' + product.description">
        {{product.name}}
    </a>

    <p *ngIf="product.description">
        {{product.description}}
    </p>
</div>



การสร้างปุ่ม Share และมี Alert เตือนแจ้งข้อความว่ามีการแชร์เรียบร้อยแล้วเมื่อทำการกดปุ่ม

เพิ่มปุ่ม Share และกำหนด Event Click ให้ไปเรียก Function share() ใน product-list.component.html
และสร้าง Function share() ใน product-list.component.ts และเรียกใช้ window.alert()
<h1>{{title}}</h1>

<div *ngFor="let product of productList">
    <a [title]="'Description: ' + product.description">
        {{product.name}}
    </a>

    <p *ngIf="product.description">
        {{product.description}}
    </p>

    <button (click)="share()">
        Share
    </button>
</div>
import { Component, OnInit } from '@angular/core';

import { products } from '../static/products';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})

export class ProductListComponent implements OnInit {

  title = 'Product List';
  productList = products;

  share() {
    window.alert("The product has been shared!");
  }

  constructor() { }

  ngOnInit() {
  }

}



สรุปพาทนี้
ใช้ ( ) ในการ Binding Event และ *ngIf สำหรับเงื่อนไขในการแสดงผล
อ่านเพิ่มเติมเกี่ยวกับ Template Syntaxhttps://angular.io/guide/template-syntax

ไม่มีความคิดเห็น:

แสดงความคิดเห็น