angular - 在 Angular 5 中将数据从父级传递给第 n 个子级

标签 angular typescript

<分区>

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

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

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;
}

结果应该是:

Luke, I am your father!

到目前为止没有什么特别的。

现在,如果我的子组件包含另一个子组件并因此充当其父组件怎么办?

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

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

最佳答案

您可以使用 3 种不同的方式将值(value)从 parent 转移到 child

  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)});
    }
    

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

关于angular - 在 Angular 5 中将数据从父级传递给第 n 个子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53450115/

相关文章:

angular - 从 child 那里访问 Angular 父路由数据

typescript - 检查输入控件是否在angular2中具有某种类型的验证器

http - Angular2 需要异步获取的结果以允许访问路由

javascript - JSONP请求错误Angular 2

angular - 如何从 Angular 事件监听器访问全局变量

javascript - Angular 6 - 自定义模态窗口内的嵌套组件

javascript - 使用 Angular,如何在两个功能之间切换?

angularjs - 如何在打开的模态组件中访问 `BsModalRef`?

javascript - 有没有更好的方法来改变javascript中的超时?

angular - 如何调试 angular2 typescript 文件