การนำทางโปรแกรมใน Angular

การเปลี่ยนไปยัง URL นั้นสามารถทำได้ไม่เพียงแต่ผ่านลิงก์เท่านั้น แต่ยังสามารถทำได้ภายในโค้ด JavaScript โดยใช้คำสั่งพิเศษอีกด้วย

สิ่งนี้ทำได้โดยใช้เซอร์วิส Router มาดูกันว่าจะทำงานกับมันอย่างไร เริ่มต้นด้วยการนำเข้า:

app/app.component.tsimport { Router } from "@angular/router";

ตอนนี้ให้ฉีด (inject) มันเข้าสู่คอมโพเนนต์ด้วยการ Dependency Injection:

app/app.component.tsexport class AppComponent {
  constructor(private router: Router) {
  
  }
}

เซอร์วิสมีเมธอด navigate ซึ่งจะนำทางไปยัง URL ที่กำหนด ลองใช้เมธอดนี้:

app/app.component.tsexport class AppComponent {
  constructor(private router: Router) {
  
  }
  
  go() {
    this.router.navigate(['/aaaa/']);
  }
}

และตอนนี้ให้เรียกเมธอด go เมื่อคลิกปุ่ม:

app/app.component.html<button (click)="go()">btn</button>
Задание 1

สร้างปุ่มสองปุ่ม ให้ปุ่มแรกนำทางไปยัง URL หนึ่ง และปุ่มที่สองนำทางไปยังอีก URL หนึ่ง