gpt4 book ai didi

angular - 如何在父组件和子组件之间进行双向数据流? ( Angular 5)

转载 作者:行者123 更新时间:2023-12-03 04:19:20 29 4
gpt4 key购买 nike

我有一个简单的代码示例,我尝试从父组件数据发送到子组件,同时在数据更改时从子组件获取数据到父组件:

父级:

@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {

parentData:string = 'start value'

}
<app-child [childData]="parentData"></app-child>

child :

@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {

@Input() childData: string;

}
<p>
{{childData}}
<br>
<input [(ngModel)]="childData" type="text">
</p>

我需要为childData注释@Output(),但它已经用@Input()注释。如何绑定(bind)变量childDataparentData

最佳答案

this article 中所述:

To create your own component that supports two-way binding, you must define an @Output property to match an @Input, but suffix it with Change.

您可以在 this stackblitz 中查看代码示例.

子组件:

<input [(ngModel)]="childData" type="text" (ngModelChange)="onModelChange($event)">
export class AppChildComponent {
@Input() childData: string;
@Output() childDataChange = new EventEmitter<string>();

onModelChange(value: string) {
this.childDataChange.emit(value);
}
}

父组件:

<app-child [(childData)]="parentData"></app-child>

关于angular - 如何在父组件和子组件之间进行双向数据流? ( Angular 5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49659746/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com