typescript - 在 Angular 5 中将数据从父组件传递给第 n 个子组件
假设我有一个父组件,它与其子组件的交互如下:
如果是这种情况,我可以使用以下语法将一些数据传递给子组件:
parent.component.ts
// imports..
selector: "app-parent",
templateURL: "./parent.component.html",
// ...
export class ParentComponent{
public statement= "I am your father"!;
}
parent.component.html
<div>
<h1>
My name is Darth Vader
</h1>
</div>
<app-child [luke] = "statement"></app-child> // child selector!
child.component.ts
// imports..
selector: "app-child",
templateURL: `<h2>{{"Luke, " + luke}}</h2>`
// ...
export class TestComponent{
@Input() public luke;
}
结果应该是:
卢克,我是你父亲!
到目前为止没什么特别的。
那么如果我的子组件包含另一个子组件,因此它充当了它的父组件,会怎样?
child.component.html
<app-secondChild></app-secondChild> // selector of second.child.component.ts!
second.child.component.html
<app-thirdChild></app-thirdChild> // selector of third.child.component.ts!
third.child.component.html
<app-fourthChild></app-fourthChild> // selector of fourth.child.component.ts!
基本上,我想把数据从父组件传递到最末层的子组件,以便激活一些 HTML 代码。
我希望这没有讲得太复杂。
答案#1
你可以用三种不同的方式将价值从父母转移给孩子
在父 .html 文件中使用输入
<app-child [user]="user"></app-child>和 child.ts 文件
export class ChildComponent implements OnInit{ @Input() user: SocialUser; }使用简单存储,storage.service.ts
public user: String = '';现在在 module.ts 文件中导入此服务,并在 parent.ts 中导入存储服务
constructor(public storageService: StorageService){} ngOnInit(){this.storageService.user = 'user_value';}在 child.ts 文件中
constructor(public storageService: StorageService){} ngOnInit(){console.log(this.storageService.user);}在 storage.service.ts 中使用 Observable
public user: Subject<any> = new BehaviorSubject<any>(null);现在在 module.ts 文件中导入此服务,并在 parent.ts 中导入存储服务
constructor(public storageService: StorageService){} ngOnInit(){this.storageService.user.next('user_value')}在 child.ts 文件中
constructor(public storageService: StorageService){} ngOnInit(){ this.storageService.user.subscribe(user=> {if(user) console.log(user)}); }
这个解决方案可能会解决你的问题。
答案#2
你可以通过输入参数将数据从父组件传递给子组件,直到最后一个子组件获得它。如果中间的组件不需要这些数据,你可以采用其他方法。我有几个选项:
你可以使用一个服务类,里面有一个属性来保存必须共享的数据。
你可以使用其他适用于共享数据存储的模式,你可能想看看 Redux 和 ngrx store: https://github.com/ngrx/store
