gpt4 book ai didi

javascript - Angular 2,如何将选项从父组件传递到子组件?

转载 作者:行者123 更新时间:2023-12-03 13:19:05 25 4
gpt4 key购买 nike

一段时间以来,我一直在寻找解决方案。我尝试了 @Input、@Query、dynamicContentLoader、@Inject、@Inject(forwardRef(()) 中的许多不同的东西,但还没有弄清楚这一点。

我的示例结构:

parent.ts

import {Component} from 'angular2/core';

@Component({
selector : 'my-app',
directives : [Child],
template : `<parent-component></parent-component>`
})

export class Parent
{
private options:any;

constructor()
{
this.options = {parentThing:true};
}
}

child.ts

import {Component} from 'angular2/core';

@Component({
selector : 'parent-component',
template : `<child-component></child-component>`
})

export class Child
{
constructor(private options:any) <- maybe I can pass them in here somehow?
{
// what I am trying to do is get options from
// the parent component at this point
// but I am not sure how to do this with Angular 2
console.log(options) <- this should come from the parent

// how can I get parent options here?
// {parentThing:true}
}
}

这是我当前在 DOM 中的 HTML 输出,所以这部分工作正常

<parent-component>
<child-component></child-component>
</parent-component>

问题总结:

如何将选项从父组件传递到子组件,并在子构造函数中使用这些选项?

最佳答案

Parent to child 是最简单的形式,但它在构造函数中不可用,仅在 ngOnInit()(或更高版本)中可用。

这只需要在子组件中使用 @Input() someField; 并使用绑定(bind)将其从父组件传递给子组件。父级中的更新在子级中更新(而不是另一个方向)

@Component({
selector: 'child-component',
template'<div>someValueFromParent: {{someValueFromParent}}</div>'
})
class ChildComponent {
@Input() someValueFromParent:string;

ngOnInit() {
console.log(this.someValue);
}
}

@Component({
selector: 'parent-component',
template: '<child-component [someValueFromParent]="someValue"></child-component>'
})
class ParentComponent {
someValue:string = 'abc';
}

要使其在构造函​​数中可用,请使用共享服务。共享服务被注入(inject)到两个组件的构造函数中。要使注入(inject)工作,服务需要在父组件或上方注册,但不能在子组件中注册。这样两者都得到相同的实例。在父级设置一个值并在客户端读取它。

@Injectable()
class SharedService {
someValue:string;
}

@Component({
selector: 'child-component',
template: '<div>someValueFromParent: {{someValueFromParent}}</div>'
})
class ChildComponent {
constructor(private sharedService:SharedService) {
this.someValue = sharedService.someValue;
}
someValue:string = 'abc';
}

@Component({
selector: 'parent-component',
providers: [SharedService],
template: '<child-component></child-component>'
})
class ParentComponent {
constructor(private sharedService:SharedService) {
sharedService.someValue = this.someValue;
}
someValue:string = 'abc';
}

更新

区别不大。对于 DI,只能使用构造函数。如果你想注入(inject)一些东西,它必须通过构造函数。 ngOnInit() 在额外的初始化发生时(比如正在处理的绑定(bind))被 Angular 调用。例如,如果您进行网络调用,那么您是否在 ngOnInit 中的构造函数中执行它并不重要,因为对服务器的调用无论如何都安排在以后(异步)。当前同步任务完成后,JavaScript 会寻找下一个计划任务并对其进行处理(依此类推)。因此,不管你把它放在哪里,在构造函数中启动的服务器调用实际上是在 ngOnInit() 之后发送的。

关于javascript - Angular 2,如何将选项从父组件传递到子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35659796/

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