组件传值
约 347 字大约 1 分钟
2026-09-16
父组件给子组件传值
在父组件给子组件传值时, 需要在子组件中使用 input 函数来接收父组件传递的值。
/src/child/child.ts
import { Component, input, signal } from '@angular/core'
@Component({
selector: 'child-component',
styleUrl: './child.css',
templateUrl: './child.html',
})
export class ChildComponent {
// ↓可以设置泛型 ↓ 可以设置默认值, 也可以不设置默认值, 直接在父组件中传值
inputText = input<string>('')
}/src/app/app.html
<!-- 直接传递和之前一样将值绑定到元素上即可 -->
<child-component [inputText]="parentText"></child-component>子组件给父组件传值
在子组件如给父组件传值时, 需要在子组件中使用 output 函数来创建一个事件
并在父组件中使用 (事件名)="方法名" 来监听子组件的事件。
/src/child/child.ts
import { Component, output, signal } from '@angular/core'
@Component({
selector: 'child-component',
styleUrl: './child.css',
templateUrl: './child.html',
})
export class ChildComponent {
// ↓ 这里的泛型是必须指定的,不然父组件不知道要接收什么类型的值,而且子组件也不知道要发出什么类型的值
textChanged = output<string>()
handleInputChange(event: Event) {
const inputElement = event.target as HTMLInputElement
this.textChanged.emit(inputElement.value)
}
}/src/app/app.ts
import { Component, signal } from '@angular/core'
@Component({
selector: 'app-root',
styleUrl: './app.css',
templateUrl: './app.html',
})
export class App {
handleChildTextChanged(newText: string) {
console.log('Received from child:', newText)
}
}/src/app/app.html
<!-- ↓ 这里也使用 $event, 不管这里收到了什么类型的数据, 这里都使用 $event -->
<child-component (textChanged)="handleChildTextChanged($event)"></child-component>