【Angular】数据在组件之间的传递方式
首先
这次总结了在Angular中常用的组件之间传递数据的方法。
※事后发现官方已经详细介绍了该内容?
如果只想浏览简要信息,请参考我的页面;如果想了解更详细信息,请查阅官方页面。
版本
-
- Angular: 9.1.11
- バージョンの確認方法については過去記事に記載しております。
结论
方程式
Angular:在指令和组件之间实现数据共享
父母將數據傳遞給子女的方式
使用 @input 在父组件和子组件之间传递值。
- 親コンポーネント
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit
{
parentData : string = "";
constructor() { }
ngOnInit() {
this.parentData = "child.componentへ渡すデータ";
}
}
<div>
<app-child [childData]="parentData"></app-child>
<div>
- 子コンポーネント
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit
{
@Input() childData: string = null;
constructor() { }
ngOnInit() {
}
}
<div>{{childData}}</div>
把数据从子代传递给父代的方法
使用@output和EventEmitter来将值传递给父组件。
- 親コンポーネント
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit
{
constructor() { }
ngOnInit() {
}
onReceiveData(event) {
console.log(event); // 子データ
}
}
<div>
<!-- eventオブジェクトでデータが渡される -->
<app-child (childData)="onReceiveData($event)"></app-child>
<div>
- 子コンポーネント
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit
{
@Output() childData = new EventEmitter<string>();
constructor() { }
ngOnInit() {
}
submitData() {
this.childData.emit("子データ");
}
}
<div>
<button (click)="submitData()">親コンポーネントへデータを渡す</button>
</div>
这是我参考的资料。
这是我引用的文献。
这个文献是我参考的。
Angular:指令和组件之间的数据共享
Angular:输入
Angular:输出
Angular:事件发射器
Angular:通过$event对象获取用户输入