本教學課程示範如何為範本加入屬性繫結(property binding),並用它將動態資料傳給元件。
你將學到什麼
- 你的應用程式將會在
Home範本中有資料繫結。 - 你的應用程式將會把資料從
Home傳送到HousingLocation。
Input 概念預覽
在這一課中,你會繼續將資料從父元件分享給子元件的過程:在範本中使用屬性繫結,將資料繫結到那些屬性上。
屬性繫結讓你能將變數連接到 Angular 範本中的 Input。資料會隨之動態繫結到該 Input。
如需更深入的說明,請參閱屬性繫結指南。
-
更新
Home範本這個步驟會為
<app-housing-location>標籤加入屬性繫結。在程式碼編輯器中:
前往
src/app/home/home.ts在
@Component裝飾器的 template 屬性中,將程式碼更新成與下列程式碼一致:加入 housingLocation 屬性繫結
import {Component} from '@angular/core'; import {HousingLocation} from '../housing-location/housing-location'; import {HousingLocationInfo} from '../housinglocation'; @Component({ selector: 'app-home', imports: [HousingLocation], template: ` <section> <form> <input type="text" placeholder="Filter by city" /> <button class="primary" type="button">Search</button> </form> </section> <section class="results"> <app-housing-location [housingLocation]="housingLocation" /> </section> `, styleUrl: './home.css', }) export class Home { readonly baseUrl = 'https://angular.dev/assets/images/tutorials/common'; housingLocation: HousingLocationInfo = { id: 9999, name: 'Test Home', city: 'Test city', state: 'ST', photo: `${this.baseUrl}/example-house.jpg`, availableUnits: 99, wifi: true, laundry: false, }; }為元件標籤加入屬性繫結時,我們使用
[attribute] = "value"語法,通知 Angular 將指派的值視為來自元件類別的屬性,而不是字串值。右側的值是
Home中屬性的名稱。
-
確認程式碼仍然可以運作
- 儲存你的變更,確認應用程式沒有任何錯誤。
- 繼續下一步之前,請先修正任何錯誤。
SUMMARY: 在這一課中,你加入了新的屬性繫結,並傳入一個類別屬性的參照。現在,HousingLocation 可以存取資料,用來自訂元件的顯示方式。
如需本課所涵蓋主題的更多資訊,請造訪: