【问题标题】:Pass boolean value from parent to child component in Angular 2在Angular 2中将布尔值从父组件传递给子组件
【发布时间】:2018-10-30 15:44:59
【问题描述】:

我正在尝试将布尔值从父组件传递到子组件,而不涉及模板文件。通过使用模板文件进行正常的父子通信我知道这一点,但不知道如何在不使用模板类的情况下进行通信。

这是我尝试过的方法,但我不确定这是否正确。

父组件.ts:

export class ParentComponent{
value1: boolean;

ngOnInit(){
if(condition){
  this.value1=true;
}
}
}

子组件.ts:

export class Childcomponent{
  @Input() value1: boolean;
}

【问题讨论】:

  • 为什么不使用模板道具呢?
  • 使用 @ViewChild 。在网上搜索示例a
  • @Soroush_Neshat ViewChild 是在 Angular 4 中引入的,但问题标题是 Angular 2
  • @AyushGupta 我看不到有问题的 angular 2 标题!
  • @Soroush_Neshat 问题已编辑。我刚刚再次编辑,将 2 放在那里,因为这很重要

标签: angular


【解决方案1】:

向父组件添加一个 observable。

 export class ParentComponent {
      public value$: Subject<boolean> = new Subject();

      public notifyChild(value: boolean) {
          this.value$.next(value);
      }
 }

将父级注入子级并订阅。

 export class ChildComponent implmenents OnDestroy {
     private destroyed: Subject = new Subject<void>;
     public constructor(parent: ParentComponent) {
         parent.value$.pipe(takeUntil(this.destroyed)).subscribe((value)=>{ ... });
     }
     public ngOnDestroy() {
          this.destroyed.next();
     }
 }

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 2017-08-04
    • 2021-10-29
    • 2016-06-10
    • 2017-08-30
    • 2020-02-04
    • 1970-01-01
    • 2018-05-01
    相关资源
    最近更新 更多