angular - 在 Angular 2 中将 bool 值从父组件传递给子组件

标签 angular

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

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

父组件.ts:

export class ParentComponent{
value1: boolean;

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

子组件.ts:

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

最佳答案

向父组件添加一个可观察对象。

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

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

将父级注入(inject)子级并订阅。

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

关于angular - 在 Angular 2 中将 bool 值从父组件传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068071/

相关文章:

javascript - API 是否应该包含用户信息?

angular - 如何隐藏/删除下划线输入 Angular Material?

node.js - Angular2嵌套路由不起作用,没有报告错误,但空白页

html - Angular4 "required"表单提交时未检查属性

angular - 警告 Angular 6 中的错误 "ReferenceError: alertify is not defined "

javascript - Angular 2/4 接口(interface)声明问题

javascript - 如何替换窗口中的 PDF 内容?

angular - 如何修复 : Angular 7 (SmartAdmin template) form validation stops working after navigation

angular - 承载 token 是否隐藏在对 REST 端点的 https 调用中

使用箭头键的 Angular2 导航