gpt4 book ai didi

angular - 理解父子组件如何处理一个对象

转载 作者:太空狗 更新时间:2023-10-29 17:19:02 24 4
gpt4 key购买 nike

我想知道 Angular 如何处理在父组件和子组件之间共享的对象。

举个简单的例子:父组件

@Component({
selector: 'app-parent',
template: `<app-children [(data)]="message"></app-children>
<div>Parent: {{message}}</div>`,
})

export class ParentComponent implements OnInit {
public message: string;

ngOnInit() {
this.message = 'Original message'
}
}

子组件

@Component({
selector: 'app-children',
template: `<div>Children: {{data}}</div>
<a (click)="changeMessage('Children message')">Click me!</a>`
})

export class ChildrenComponent {
@Input() public data: string;
changeMessage(message: string) {
this.data = message;
}
}

当我点击“点击我!”链接,我只看到子消息发生变化,但没有看到父消息。不是同一个对象吗?

最佳答案

考虑到您应该从 child 发出更改后的值,并且您的发射器名称应该是 [your bind var name]+'Change' 这样它就可以工作了:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-root',
template: `<app-children [(data)]="message"></app-children>
<div>Parent: {{message}}</div>`,
})

export class AppComponent {
public message: string;

ngOnInit() {
this.message = 'Original message'
}
}

@Component({
selector: 'app-children',
template: `<div>Children: {{data}}</div>
<a (click)="changeMessage('Children message')">Click me!</a>`
})

export class ChildComponent {
@Input() public data: string;
@Output() dataChange= new EventEmitter<string>();
changeMessage(message: string) {
this.data = message;
this.dataChange.emit(this.data);
}
}

检查 DEMOcreating custom two-way data bindings .

关于angular - 理解父子组件如何处理一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502613/

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