【问题标题】:Pass data from parent to nth child in Angular 5 [duplicate]在Angular 5中将数据从父母传递给第n个孩子[重复]
【发布时间】:2019-04-26 06:26:34
【问题描述】:

假设我有一个与其子组件交互的父组件,例如:

如果是这种情况,我可以使用以下语法将一些数据传递给孩子:

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 代码。

我希望这没有解释得太复杂。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以使用 3 种不同的方式将价值从父母转移到孩子

    1. 在父 .html 文件中使用输入

      <app-child [user]="user"></app-child>
      

      和 child.ts 文件

      export class ChildComponent implements OnInit{
         @Input() user: SocialUser;
      }
      
    2. 使用简单存储,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);}
      
    3. 在 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)});
      }
      

    此解决方案可能会解决您的问题。

    【讨论】:

    • 谢谢!这也帮助了我。现在,我只需要找到一种方法,用服务的 HTML 代码替换子项中给定 div 的 HTML 代码。我知道我必须使用类似 document.getElementByID("replaceIt").innerHTML = "..." 的东西,但这是另一个话题。谢谢!
    【解决方案2】:

    您可以使用输入参数将数据从父级传递给子级,直到最后一个子级得到它。如果中间的组件不需要这些数据,您可以采取其他方法。我有几个选择:

    1. 您可以使用带有属性的服务类,该属性包含必须共享的数据。

    2. 您可以使用与共享数据存储一起使用的其他模式,您可能想看看 Redux 和 ngrx 存储:https://github.com/ngrx/store

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2023-02-08
      • 2018-05-03
      • 2020-07-22
      相关资源
      最近更新 更多