在Angular中,父組件可以通過(guò)在模板中使用子組件的選擇器來(lái)調(diào)用子組件。以下是一個(gè)簡(jiǎn)單的示例:
在父組件的模板中,使用子組件的選擇器來(lái)調(diào)用子組件:
<app-child></app-child>
在子組件中,可以通過(guò)使用@Input裝飾器來(lái)接收父組件傳遞的數(shù)據(jù):
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ childData }}</p>'
})
export class ChildComponent {
@Input() childData: string;
}
在父組件的類(lèi)中,可以通過(guò)給子組件的屬性賦值來(lái)傳遞數(shù)據(jù)給子組件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: '<app-child [childData]="parentData"></app-child>'
})
export class ParentComponent {
parentData: string = 'Hello from parent component';
}
在這個(gè)示例中,父組件通過(guò)給子組件的childData
屬性賦值來(lái)傳遞數(shù)據(jù)給子組件。子組件通過(guò)使用插值表達(dá)式{{ childData }}
來(lái)顯示接收到的數(shù)據(jù)。
通過(guò)這種方式,父組件可以直接調(diào)用子組件并傳遞數(shù)據(jù)給子組件。