gpt4 book ai didi

angular - 在 Angular 中将数据从父级传递给孙级的正确方法。那是对的吗?

转载 作者:行者123 更新时间:2023-12-05 02:33:58 26 4
gpt4 key购买 nike

我正在尝试将数据从父组件传递到子组件。我有这样的东西:

父组件:

@Component({
selector: 'foo-parent',
templateUrl: './foo-parent.component.html',
styleUrls: ['./foo-parent.component.scss'],
})
export class FooParent {

@Input() data: any;

constructor() { }

}

父级从执行所有逻辑的另一个库接收数据。

孙组件:

@Component({
selector: 'foo-grand-child',
templateUrl: './foo-grand-child.component.html',
styleUrls: ['./foo-grand-child.component.sass'],
})

export class FooGrandChild {

data: any;

constructor(private fooParent: FooParent) {
this.data = this.fooParent.fooGrandChildData;
}

这种方式可以正常工作,但我是新手,我不知道这样做是否正确。除了桥接 parent > child > grandchild 组件之外,还有其他方法吗?

最佳答案

我不认为这是在组件之间传递数据的 Angular 方式。由于您已经知道组件之间的关系(这很好),您可以选择组件之间正确的通信方法。

我建议阅读<强> https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/

至于您的用例。 孙辈的 parent

我建议使用 Service,它由您的 Parent ComponentGrandchild Component 设置 field/property code> 获取那个字段/属性,而不是直接注入(inject) 父组件到您的孙组件

父组件

@Component({
selector: 'foo-parent',
templateUrl: './foo-parent.component.html',
styleUrls: ['./foo-parent.component.scss'],
})
export class FooParent implements OnInit {

constructor(private sharedtestService: SharedTestService) { }

ngOnInit(): void {
this.sharedtestService.setTestData('string');
}
}

孙组件

@Component({
selector: 'foo-grand-child',
templateUrl: './foo-grand-child.component.html',
styleUrls: ['./foo-grand-child.component.sass'],
})

export class FooGrandChild implements OnInit {

data: string;

constructor(private sharedtestService: SharedTestService) {}

ngOnInit(): void {
this.data = this.sharedtestService.getTestData();
}
}

共享服务

@Injectable({
providedIn: 'root'
})
export class SharedTestService {
testData: string;
constructor() {}

setTestData(temp: string): void {
return this.testData = temp;
}

getTestData(): string {
return this.testData;
}
}

我还建议查看 Observables 以及如何订阅它们,如果您希望您的 GrandChildren Component 自动监听您的 Parent 所做的更改组件

关于angular - 在 Angular 中将数据从父级传递给孙级的正确方法。那是对的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70845228/

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