我正在尝试将数据从父组件传递到子组件。我有这样的东西:
父组件:
@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;
}
这种方法是正确的,但我是一个新手,我不知道这是否是正确的方法。除了桥接父母,还有其他方法吗;child>孙组件?
我不认为这是在组件之间进行数据通信的Angular
方式。正如您已经知道组件之间的关系(这很好(,您可以选择组件之间正确的通信方法。
我建议阅读https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/
至于您的用例孙子女的父母。
我建议使用Service
,即通过Parent Component
设置field/property
,然后Grandchild Component
获得field/property
,而不是直接Injecting
Grandchild Component
中的Parent Component
父组件
@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;
}
}
如果您希望GrandChildren Component
自动监听Parent Component
所做的更改,我还建议查看Observables
以及如何订阅它们。
有几件事,首先,如果您想将某个东西从父级传递给子级,并从子级传递给它的子级(父组件的孙子级((在您接收数据的地方(,我们会在父级中使用@Input((装饰器@Input((数据在@out((数据出。这就是为什么@Input((应该用于子组件的原因。一旦在子组件中有了@Input,就可以通过HTML将值传递给该变量。我给你看一个例子:
儿童:
@Component({
selector: 'child-sample-component',
templateUrl: './child-sample-component.component.html',
})
export class ChildSampleComponenet {
@Input() childObject;
}
父级(html(:
<child-sample-component [childObject]="parentObject">
</child-sample-component>
请注意,在子级中,我们使用带有childObject变量的@Input,在父级html中,我们将值赋予带有parentObject父级变量的childObject,该变量将包含任何内容。
还有其他方法,比如使用服务等。但你应该边走边学。这里有几个有趣的链接。
https://angular.io/guide/inputs-outputs
https://angular.io/guide/architecture-services